Python 3.x 熊猫用元组将dataframe列扩展为多个列和行

Python 3.x 熊猫用元组将dataframe列扩展为多个列和行,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,我有一个数据框,其中一列包含元素,这些元素是一个包含多个元组的列表。我想将每个元组转换为每个元素的一列,并为每个元组创建一个新行。这段代码显示了我的意思和我提出的解决方案: 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','th

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

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)
输出为:

  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

不幸的是,我的解决方案需要2小时才能在55000行上运行!有更有效的方法吗?

我们先分解列,然后分解行

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

我们先分解列,然后分解行

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

哇!这将时间缩短到680ms。。。并介绍我“爆炸”。TnxI在这里问了一个与此过程相反的问题:您还可以向pd.DataFrame参数中添加列=['a','B','C'],以调整col namesWow!这将时间缩短到680ms。。。并介绍我“爆炸”。TnxI在这里问了一个与此过程相反的问题:您还可以向pd.DataFrame参数添加列=['a','B','C'],以调整列名称