pandas 用元组将数据框列扩展为多列和多行

Mik*_*19x 1 dataframe python-3.x pandas

我有一个数据框,其中一列包含元素,这些元素是包含多个元组的列表。我想将每个元组转换为每个元素的一列,并为每个元组创建一个新行。所以这段代码显示了我的意思和我想出的解决方案:

import numpy as np
import pandas as pd

a = pd.DataFrame(data=[['a','b',[(1,2,3),(6,7,8)]],
                      ['c','d',[(10,20,30)]]], columns=['one','two','three'])

df2 = pd.DataFrame(columns=['one', 'two', 'A', 'B','C'])

print(a)

for index,item in a.iterrows():
    for xtup in item.three:
        temp = pd.Series(item)
        temp['A'] = xtup[0]
        temp['B'] = xtup[1]
        temp['C'] = xtup[2]
        temp = temp.drop('three')
        df2 = df2.append(temp)

print(df2)
Run Code Online (Sandbox Code Playgroud)

输出是:

  one two                   three
0   a   b  [(1, 2, 3), (6, 7, 8)]
1   c   d          [(10, 20, 30)]



  one two   A   B   C
0   a   b   1   2   3
0   a   b   6   7   8
1   c   d  10  20  30
Run Code Online (Sandbox Code Playgroud)

不幸的是,我的解决方案需要 2 小时才能在 55,000 行上运行!有没有更有效的方法来做到这一点?

WeN*_*Ben 5

我们先爆炸列然后爆炸行

a=a.explode('three')
a=pd.concat([a,pd.DataFrame(a.pop('three').tolist(),index=a.index)],axis=1)
  one two   0   1   2
0   a   b   1   2   3
0   a   b   6   7   8
1   c   d  10  20  30
Run Code Online (Sandbox Code Playgroud)