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"}
]
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With