以上链接为我的回答提供了一些解决方案
但我有同样的问题,输入方面差别不大。我的DF:
df = pd.DataFrame({'a':[1,2,3], 'b':[[{'c':1},{'c':3}], {'d':3}, {'c':5, 'd':6}]})
我的词典再次包含Key" b"。
的词条列表我预期的O / P:
[a c c1 d
0 1 1.0 3 NaN
1 2 NaN NaN 3.0
2 3 5.0 NaN 6.0][1]
你能帮忙吗?
答案 0 :(得分:0)
您可以使用:
#convert to list of df with condition for add list
L = [pd.DataFrame(x) if isinstance(x, list) else pd.DataFrame([x]) for x in df['b']]
#join together, reshape and remove all NaNs columns
df1 = pd.concat(L, keys=df.index).unstack().dropna(how='all', axis=1)
#flattening MultiIndex in columns
df1.columns = ['{}{}'.format(a,b) for a,b in df1.columns]
print (df1)
c0 c1 d0
0 1.0 3.0 NaN
1 NaN NaN 3.0
2 5.0 NaN 6.0
#remove original column b and join df1
df = df.drop('b',1).join(df1)
print (df)
a c0 c1 d0
0 1 1.0 3.0 NaN
1 2 NaN NaN 3.0
2 3 5.0 NaN 6.0