0

I am using pandas to read a CSV which contains a phone_number field (string), however, I need to convert this field into the below JSON format [{'phone_number':'+01 373643222'}] and put it under a new column name called phone_numbers, how can I do that?

Searched online but the examples I found are converting the all the columns into JSON by using to_json() which is apparently cannot solve my case.

Below is an example

import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 
                   'phone_number': ['+1 569-483-2388', '+1 555-555-1212', '+1 432-867-5309']})
onegun
  • 803
  • 1
  • 10
  • 27
  • please create an example for your question, check [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – anky Sep 22 '19 at 16:08
  • tolist() should do the job. Check answer here: https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column – Wojciech Sabała Sep 22 '19 at 16:09
  • `[df["phone_number"].to_json()]` will convert the Series to json in a list – Alex Sep 22 '19 at 16:10
  • it is not working by doing `df['phone_numbers'] = [df["phone_number"].to_json()]` – onegun Sep 22 '19 at 16:13
  • do you need: `df['phone_numbers']=[f'phone_number:{i}' for i in df['phone_number']]` or `df['phone_numbers']=[f'[phone_number:{i}]' for i in df['phone_number']]` ? – anky Sep 22 '19 at 16:18

1 Answers1

1

use map function like this

df["phone_numbers"] = df["phone_number"].map(lambda x: [{"phone_number": x}] )

display(df)
Dev Khadka
  • 5,142
  • 4
  • 19
  • 33