pandas 有效地将数据帧与不匹配的分类列和多索引级别连接起来



如果我有两个数据帧,其中分类列和 MultiIndex 级别不匹配,如何将它们有效地连接到单个数据帧中?

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

感谢您的帮助!

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'])

最新更新