【发布时间】: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