Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert columns of lists to column of dictionary [duplicate]

Tags:

python

pandas

In a large pandas Dataframe, I have three columns (fruit, vegetable, and first_name). The values of these columns are lists.

From the lists, I want to create one new column with a list of dictionaries for each row of the DataFrame.

I have three columns (fruit, vegetable, and first_name) with each row having lists as their values.

First row of my dataframe:

df = pd.DataFrame({
 "fruit": [["Apple", "Banana","Pear","Grape","Pineapple"]],
 "vegetable": [["Celery","Onion","Potato","Broccoli","Sprouts"]],
 "first_name": [["Sam", "Beth", "John", "Daisy", "Jane"]]
})

How do I transform the three columns to one column and have the value look like this instead?

[
   {"fruit": "Apple", "vegetable":"Celery", "first_name":"Sam"}, 
   {"fruit": "Banana", "vegetable":"Onion", "first_name":"Beth"},
   {"fruit": "Pear", "vegetable":"Potato", "first_name":"John"},
   {"fruit": "Grape", "vegetable":"Broccoli", "first_name":"Daisy"},
   {"fruit": "Pineapple", "vegetable":"Sprouts", "first_name":"Jane"}
]
like image 694
Kevin Avatar asked Mar 02 '23 05:03

Kevin


1 Answers

IIUC you can do it with (1) .explode() and (2) .to_dict()

df.apply(pd.Series.explode).to_dict(orient='records')
#output:
[{'fruit': 'Apple', 'vegetable': 'Celery', 'first_name': 'Sam'},
 {'fruit': 'Banana', 'vegetable': 'Onion', 'first_name': 'Beth'},
 {'fruit': 'Pear', 'vegetable': 'Potato', 'first_name': 'John'},
 {'fruit': 'Grape', 'vegetable': 'Broccoli', 'first_name': 'Daisy'},
 {'fruit': 'Pineapple', 'vegetable': 'Sprouts', 'first_name': 'Jane'}]
like image 159
Terry Avatar answered May 03 '23 00:05

Terry