当前位置: 代码迷 >> python >> 熊猫有效地将DataFrame与不匹配的分类列和MultiIndex级别连接
  详细解决方案

熊猫有效地将DataFrame与不匹配的分类列和MultiIndex级别连接

热度:107   发布时间:2023-07-14 09:52:19.0

如果我有两个具有不匹配的分类列和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

以下是示例DataFrames:

>>> 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的数据,因此将它们转换为一致的类别将是一项艰巨的任务。 希望可以避免。

谢谢您的帮助!

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'])
  相关解决方案