将字典拆分为df中的各个列 [英] Split dictionary into individual columns in a df
本文介绍了将字典拆分为df中的各个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下df
,其值是字典:
I have the following df
whose values are dictionaries:
tests
SO4 {'Mon': 6, 'Tues': 6, 'Wed': 7}
CH3 {'Mon': 0, 'Tues': 8, 'Wed': 10}
我想获得所需的输出:
0 1 2
SO4 'Mon': 6 'Tues': 6 'Wed': 7
CH3 'Mon': 0 'Tues': 8 'Wed': 10
如何将字典分为几列?
我已经看到使用rsplit
函数将字符串拆分成列,但是不确定如何将字典用作值.
I have seen the columns split of strings using rsplit
function but not sure on how to apply it in the case of dictionaries as values.
推荐答案
我认为更好的方法是使用:
I think better is use:
df = pd.DataFrame(df['tests'].values.tolist(), index=df.index)
print (df)
Mon Tues Wed
SO4 6 6 7
CH3 0 8 10
但是如果真的需要它(但是字典在设计上是无法排序的,那么可能会得到不同的输出):
But if really need it (but dicts are by design not sortable, so maybe get different output):
df = df['tests'].astype(str).str.strip('{}').str.split(', ', expand=True)
print (df)
0 1 2
SO4 'Mon': 6 'Wed': 7 'Tues': 6
CH3 'Mon': 0 'Wed': 10 'Tues': 8
这篇关于将字典拆分为df中的各个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文