我有以下数据帧:
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
解决方法:
关于你的数据,
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], 's': ['a','b','c','d','e']})
df:
id s scene
0 1 a {'kitchen': '0.297', 'living': '0.515'}
1 2 b {'kitchen': '0.401', 'study': '0.005'}
2 3 c {'study': '0.913'}
3 4 d {}
4 5 e {'others': '0'}
有两种方法可以做到这一点,
>在一行中,您必须将除“场景”之外的所有列名称输入到set_index函数
df = df.set_index(['id', 's'])['scene'].apply(pd.Series).fillna(0).reset_index()
这将输出:
id s kitchen living study others
0 1 a 0.297 0.515 0 0
1 2 b 0.401 0 0.005 0
2 3 c 0 0 0.913 0
3 4 d 0 0 0 0
4 5 e 0 0 0 0
>在两行中,您可以在其中创建例外结果并将其连接到原始数据框.
df1 = df.scene.apply(pd.Series).fillna(0)
df = pd.concat([df, df1], axis=1)
这使,
id s scene kitchen living study others
0 1 a {'kitchen': '0.297', 'living': '0.515'} 0.297 0.515 0 0
1 2 b {'kitchen': '0.401', 'study': '0.005'} 0.401 0 0.005 0
2 3 c {'study': '0.913'} 0 0 0.913 0
3 4 d {} 0 0 0 0
4 5 e {'others': '0'} 0 0 0 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。