我有MultiIndex数据帧(表1),我想合并来自不是multiIndex的另一个数据帧(表2)的特定列。
表1的示例:
>>> name 2020-10-21 2020-10-22 ...
Column 9 10 11 12 9 10 11 12
0 A5 2.1 2.2 2.4 2.8 5.4 3.4 1.1 7.3
1 B9 7.2 1.2 14.5 7.5 3.4 5.2 6.4 8.1
2 C3 1.1 6.5 8.4 9.1 1.1 4.3 6.5 8.7
...
表2的示例:
>>>name indc control code
0 A5 0.32 yes 1
1 C3 0.11 no 2
2 B18 0.23 yes 2
3 B9 0.45 no 3
我想基于表2中的键“名称”(和表1中的“索引”)合并“代码”列,以获取te名称旁边的代码:
>>> index 2020-10-21 2020-10-22 ...
Column code 9 10 11 12 9 10 11 12
0 A5 1 2.1 2.2 2.4 2.8 5.4 3.4 1.1 7.3
1 B9 3 7.2 1.2 14.5 7.5 3.4 5.2 6.4 8.1
2 C3 2 1.1 6.5 8.4 9.1 1.1 4.3 6.5 8.7
...
我知道当索引不是multindex级别时如何合并,然后这样做:
df = table1.merge(table2[['code','name']], how = 'left',
left_on = 'index', right_on = 'name')
但是现在我得到了错误:
UserWarning:在不同级别之间合并可能会产生意外的结果(左侧2级,右侧1级)警告。warn(msg,UserWarning)
接着:
ValueError:“索引”不在列表中
当我打印列时,我可以看到你就像元组,但是我不知道为什么它说索引不在列表中,就像我打印表1的列时得到的那样:
Index([ ('index', ''), (2020-10-22, 9)...
所以我有点困惑。
我的最终目标:基于“名称”和“索引”列合并代码列
为了满足MultiIndex
两个中DataFrame
的正确工作需求:
df2 = table2[['code','name']].rename(columns={'name':'index'})
df2.columns = pd.MultiIndex.from_product([df2.columns, ['']])
df = table1.merge(df2, how = 'left', on = [('index', '')])
#if necessary reorder columns names
cols = df.columns[:1].tolist() + df.columns[-1:].tolist() + df.columns[1:-1].tolist()
df = df[cols]
print (df)
index code 2020-10-21 2020-10-22
9 10 11 12 9 10 11 12
0 A5 1 2.1 2.2 2.4 2.8 5.4 3.4 1.1 7.3
1 B9 3 7.2 1.2 14.5 7.5 3.4 5.2 6.4 8.1
2 C3 2 1.1 6.5 8.4 9.1 1.1 4.3 6.5 8.7
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句