pandas 将字典列表爆炸成行 [英] Pandas explode list of dictionaries into rows
本文介绍了 pandas 将字典列表爆炸成行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
拥有这个:
items, name
0 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], this }
1 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], that }
但是希望将字典对象的列表分解成(展平?)到实际的行中,如下所示:
But would like to have the list of dictionary objects exploded into (flattened?) into actual rows like this:
a, b, name
0 { 2, 1, this}
1 { 4, 3, this}
0 { 2, 1, that}
1 { 4, 3, that}
一直在尝试使用melt
,但是没有运气,有什么主意吗?建议?
Having been trying to use melt
but with no luck, any ideas? suggestions?
推荐答案
使用 concat
也许更干净:
Another way to use concat
perhaps more cleanly:
In [11]: pd.concat(df.group.apply(pd.DataFrame).tolist(), keys=df["name"])
Out[11]:
a b
name
this 0 2 1
1 4 3
that 0 2 1
1 4 3
In [12]: pd.concat(df.group.apply(pd.DataFrame).tolist(),
keys=df["name"]).reset_index(level="name")
Out[12]:
name a b
0 this 2 1
1 this 4 3
0 that 2 1
1 that 4 3
这篇关于 pandas 将字典列表爆炸成行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文