且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将包含字典列表的列转换为pandas数据框中的多个列

更新时间:2022-03-23 04:01:34

您可以使用 concat list comprehension:

df = pd.concat([pd.DataFrame(x) for x in df['b']], keys=df['a'])
       .reset_index(level=1, drop=True).reset_index()

print (df)
   a   c   d
0  1   1   5
1  1   3   7
2  2  10  50

如果索引是唯一的,则可以使用 join 用于所有列:

If index is unique, then is possible use join for all columns:

df1 = pd.concat([pd.DataFrame(x) for x in df['b']], keys=df.index)
        .reset_index(level=1,drop=True)
df = df.drop('b', axis=1).join(df1).reset_index(drop=True)
print (df)
   a   c   d
0  1   1   5
1  1   3   7
2  2  10  50

我尝试简化解决方案:

l = df['b'].str.len()
df1 = pd.DataFrame(np.concatenate(df['b']).tolist(), index=np.repeat(df.index, l))
df = df.drop('b', axis=1).join(df1).reset_index(drop=True)
print (df)
   a   c   d
0  1   1   5
1  1   3   7
2  2  10  50