Python 将单索引数据帧连接到多索引数据帧
我有两个数据帧,结构类似Python 将单索引数据帧连接到多索引数据帧,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有两个数据帧,结构类似 # df1 data1 data2 id feature_count 12345 1 111 888 2 222 999 3 333 101010 45678 0 444 111111 2
# 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
及
基于此,我似乎应该能够简单地执行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"
然而,我实际得到的是未实现error:Index.\u非唯一索引上的连接级别在Pandas 1.0.5中未实现
这似乎并不复杂,但我显然误解了一些事情。我想要的只是将df2
中的唯一映射列附加到df1
的(保证现有映射)第一个索引上,因为您只需要映射一列,只需执行以下操作:
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"
我不能重复你的错误。我也有1.0.5版。您的示例代码适用于我。您的示例代码是否适用于您,或者您是否在较大的数据集上得到了错误?它是从SQL查询中拉入的一个更大的数据集。在我接受了答案后(一个不同的错误被证明更具信息性),我认为查询出现了意外的重复(我很惊讶熊猫让我给它指定了一个索引)。你的第一个案例仍然给了我一个错误,但你的第二个案例非常有效。谢谢
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"