在Python中将一个字符串列拆分为多个列
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Python中将一个字符串列拆分为多个列,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2090字,纯文字阅读大概需要3分钟。
内容图文
我有以下数据帧:
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
内容总结
以上是互联网集市为您收集整理的在Python中将一个字符串列拆分为多个列全部内容,希望文章能够帮你解决在Python中将一个字符串列拆分为多个列所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。