【问题标题】:pandas efficiently concatenating DataFrames with non-matching categorical columns and MultiIndex levelspandas 有效地将 DataFrames 与不匹配的分类列和 MultiIndex 级别连接起来
【发布时间】:2019-02-26 15:56:17
【问题描述】:

如果我有两个分类列和 MultiIndex 级别不匹配的 DataFrame,我怎样才能有效地将它们连接成一个 DataFrame?

import pandas as pd
t = pd.DataFrame(data={'i1':['a','a','a','a','b','b','b','b','c','c','c','c'], 
                       'i2':[0,1,2,3,0,1,2,3,0,1,2,3], 
                       'x':[1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.],
                       'y':['x','y','x','y','x','y','x','y','x','y','x','y']})
t['i1'] = t['i1'].astype('category')
t['y']  = t['y' ].astype('category')
t.set_index(['i1','i2'], inplace=True)
t.sort_index(inplace=True)
print(t.index.levels[0]) # :-)

t2 = pd.DataFrame(data={'i1':['d','d','d','d'], 
                        'i2':[0,1,2,3], 
                        'x':[13.,14.,15.,16.],
                        'y':['x','z','x','z']})
t2['i1'] = t2['i1'].astype('category')
t2['y']  = t2['y' ].astype('category')
t2.set_index(['i1','i2'], inplace=True)
t2.sort_index(inplace=True)

pd.concat([t,t2], sort=False)
# TypeError: categories must match existing categories when appending

这里是示例数据帧:

>>> t
          x  y
i1 i2         
a  0    1.0  x
   1    2.0  y
   2    3.0  x
   3    4.0  y
b  0    5.0  x
   1    6.0  y
   2    7.0  x
   3    8.0  y
c  0    9.0  x
   1   10.0  y
   2   11.0  x
   3   12.0  y
>>> t2
          x  y
i1 i2         
d  0   13.0  x
   1   14.0  z
   2   15.0  x
   3   16.0  z

我有数千个数据文件和 TB 数据,因此将它们转换为具有一致的类别将是一项艰巨的任务。希望可以避免。

感谢您的帮助!

【问题讨论】:

    标签: python pandas concatenation multi-index categorical-data


    【解决方案1】:
    t = t.reset_index()
    t2 = t2.reset_index()
    t3 = pd.concat([t, t2], ignore_index=True)
    t3 = t3.set_index(['i1', 'i2'])
    
               x    y
    i1  i2      
    a   0   1.0     x
        1   2.0     y
        2   3.0     x
        3   4.0     y
    b   0   5.0     x
        1   6.0     y
        2   7.0     x
        3   8.0     y
    c   0   9.0     x
        1   10.0    y
        2   11.0    x
        3   12.0    y
    d   0   13.0    x
        1   14.0    z
        2   15.0    x
        3   16.0    z
    

    该示例未提供原始数据示例或导入方式。重新考虑处理数据的方法可能会更有效。

    例如:

    path_to_files = r'c:\data\*.csv'
    all_files = glob.glob(path_to_files)
    df = pd.concat((pd.read_csv(f) for f in all_files))
    df = df.set_index(['i1', 'i2'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2018-12-16
      • 2018-10-27
      • 2017-10-16
      • 2018-06-24
      • 2019-10-18
      相关资源
      最近更新 更多