带有字典条目的拆分/分解熊猫列

问题描述 投票:1回答:2

我有一个这样的数据框。

index          column1
e1             {u'c680': 5, u'c681': 1, u'c682': 2...
e2             {u'c780': 6, u'c781': 2, u'c782': 1...
e3             {u'c880': 2, u'c881': 4, u'c882': 2...
e4             {u'c980': 4, u'c981': 2, u'c982': 3...

现在我想将column1中的字典扩展到如下所示的各个列。

index   colname           c681
e1        c680              5
e1        c681              1
e1        c682              2
e2        c780              6
e2        c781              2
e2        c782              1

我在建议使用的地方经历了两个类似的答案:

df.column1.apply(pd.Series)

但是,这会以不同的方式爆炸该列...是否有任何方法可以使列显示得更好?

python pandas
2个回答
1
投票

您可以在列表理解中展平字典的Series并传递给DataFrame构造函数,如果index不在输入数据的非列中,则解决方案有效:

df1 = pd.DataFrame([(k, ) + y for k, v in df.column1.items() for y in v.items()], 
                    columns=['idx','colname', 'c681'])
print (df1)
   idx colname  c681
0   e1    c680     5
1   e1    c681     1
2   e1    c682     2
3   e2    c780     6
4   e2    c781     2
5   e2    c782     1
6   e3    c880     2
7   e3    c881     4
8   e3    c882     2
9   e4    c980     4
10  e4    c981     2
11  e4    c982     3

2
投票

您可以将mapmap字典,用dict.items展平所得的元组并重建数据帧:

itertools.chain
© www.soinside.com 2019 - 2024. All rights reserved.