首页 > 解决方案 > 熊猫用元组将数据框列扩展为多列和多行

问题描述

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

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 个小时才能在 55,000 行上运行!有没有更有效的方法来做到这一点?

标签: python-3.xpandasdataframe

解决方案


我们先分解列然后分解行

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

推荐阅读