有这个:
items, name
0 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], this }
1 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], that }
但是希望将字典对象列表分解成(展平?)成像这样的实际行:
a, b, name
0 { 2, 1, this}
1 { 4, 3, this}
0 { 2, 1, that}
1 { 4, 3, that}
一直在尝试使用 melt
但没有成功,有什么想法吗?有什么建议吗?
产生DataFrame的数据:
data = {'items': [[{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}]], 'name': ['this', 'that']}
最佳答案
另一种使用方式 concat
也许更干净:
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
关于python - Pandas 将字典列表分解成行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148683/