python把字符串拆分为四个字符串_在Python中将一个字符串列拆分为多个列

本文介绍了如何使用Pandas处理含有字符串字典的数据帧,将其拆分为多个单独的列,并填充缺失值。通过示例展示了两种方法,一种是一行代码实现,另一种是分两步操作,最后将结果合并到原始数据框中。

我有以下数据帧:

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,pandas

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值