小编Kev*_*vin的帖子

将列表列转换为字典列

在一个大的熊猫数据帧,我有三列(fruitvegetable,和first_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"]]
})
Run Code Online (Sandbox Code Playgroud)

如何将三列转换为一列并使值看起来像这样?

[
   {"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"}
]
Run Code Online (Sandbox Code Playgroud)

python pandas

4
推荐指数
1
解决办法
1250
查看次数

标签 统计

pandas ×1

python ×1