gpt4 book ai didi

python - 将列表列转换为字典列

转载 作者:行者123 更新时间:2023-12-03 20:25:10 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Split cell into multiple rows in pandas dataframe

(5 个回答)



Pandas DataFrame to List of Dictionaries

(5 个回答)


去年关闭。




在 Pandas 数据框中,我有三列( fruitvegetablefirst_name )。这些列的值是列表。
从列表中,我想为 DataFrame 的每一行创建一个包含字典列表的新列。
我有三列( fruitvegetablefirst_name ),每行都有列表作为它们的值。
我的数据框的第一行:

df = pd.DataFrame({
"fruit": [["Apple", "Banana","Pear","Grape","Pineapple"]],
"vegetable": [["Celery","Onion","Potato","Broccoli","Sprouts"]],
"first_name": [["Sam", "Beth", "John", "Daisy", "Jane"]]
})
如何将三列转换为一列并使值看起来像这样?
[
{"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 你可以用 (1) .explode()和 (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'}]

关于python - 将列表列转换为字典列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63021154/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com