Pandas 将字典列表分解为行

De *_*rez 5 python pandas

有这个:

                                  items, name
0   { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], this }
1   { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], that }
Run Code Online (Sandbox Code Playgroud)

但是想要将字典对象列表分解成(扁平化?)成这样的实际行:

    a, b, name
0   { 2, 1, this}
1   { 4, 3, this}
0   { 2, 1, that}
1   { 4, 3, that}
Run Code Online (Sandbox Code Playgroud)

一直在尝试使用melt但没有运气,有什么想法吗?建议?

And*_*den 5

另一种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
Run Code Online (Sandbox Code Playgroud)

  • 看起来不错,但我得到了这个“AttributeError:'DataFrame'对象没有属性'group'”?也许是我的熊猫版本? (2认同)