gpt4 book ai didi

python - 在 Python 中将一个字符串列拆分为多个列

转载 作者:太空狗 更新时间:2023-10-30 02:24:41 25 4
gpt4 key购买 nike

我有以下数据框:

df = pd.DataFrame({'scene':[{"living":"0.515","kitchen":"0.297"}, {"kitchen":"0.401","study":"0.005"}, {"study":"0.913"}, {}, {"others":"0"}], 'id':[1, 2, 3 ,4, 5]}) 

id scene
01 {"living":"0.515","kitchen":"0.297"}
02 {"kitchen":"0.401","study":"0.005"}
03 {"study":"0.913"}
04 {}
05 {"others":"0"}

我想创建一个新的数据框,如下所示,有人可以帮助我使用 Pandas 创建它吗?

id      living     kitchen     study     others
01 0.515 0.297 0 0
02 0 0.401 0.005 0
03 0 0 0.913 0
04 0 0 0 0
05 0 0 0 0

最佳答案

简单的解决方案是将您的 scene 列转换为字典列表,并使用默认构造函数创建新的数据框:

pd.DataFrame(df.scene.tolist()).fillna(0)

结果:

  kitchen living others  study
0 0.297 0.515 0 0
1 0.401 0 0 0.005
2 0 0 0 0.913
3 0 0 0 0
4 0 0 0 0

创建 DataFrame 的“默认”方法之一是使用字典列表。在这种情况下,列表的每个字典将被转换为单独的行,字典的每个键将用于列标题。

关于python - 在 Python 中将一个字符串列拆分为多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997410/

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