我有两个数据框,结构类似
# df1
data1 data2
id feature_count
12345 1 111 888
2 222 999
3 333 101010
45678 0 444 111111
2 555 121212
3 666 131313
4 777 141414
和
# df2
descriptor
id
12345 "foo"
45678 "bar"
基于this solution,看来我应该能够做df1.join(df2)
以获得期望的结果
#joined
data1 data2 descriptor
id feature_count
12345 1 111 888 "foo"
2 222 999 "foo"
3 333 101010 "foo"
45678 0 444 111111 "bar"
2 555 121212 "bar"
3 666 131313 "bar"
4 777 141414 "bar"
但是,我实际上得到的是熊猫1.0.5中的NotImplementedError: Index._join_level on non-unique index is not implemented
。
这似乎不应该太复杂,但是我显然误会了一些东西。我要寻找的只是将df2
中唯一映射的列追加到df1
的(保证现有映射)第一个索引上。
答案 0 :(得分:1)
由于您只需要映射一列,因此只需执行以下操作:
df1['descriptor'] = df1.index.get_level_values('id').map(df2['descriptor'])
通常,您可以临时重置其他索引,加入数据框并重新设置它:
df1.reset_index('feature_count').join(df2).set_index('feature_count', append=True)
输出:
data1 data2 descriptor
id feature_count
12345 1 111 888 "foo"
2 222 999 "foo"
3 333 101010 "foo"
45678 0 444 111111 "bar"
2 555 121212 "bar"
3 666 131313 "bar"
4 777 141414 "bar"