目前Pandas合并存在问题吗?

3

使用外连接合并两个表。假设:

df1 = ['productID', 'Name']

df2 = ['userID', 'productID', 'usage']

我尝试使用 pandas 的 merge 函数进行外连接。

pd.merge(df1, df2[['userID','productID', 'usage']], on='productID', how = 'outer')

然而,我收到的错误消息是:
'productID' is both an index level and a column label, which is ambiguous.

我在谷歌上搜索了这个错误消息,并看到一个开放性 [issue]: https://github.com/facebook/prophet/issues/891

有解决方法吗?


“'productID'是索引级别和列标签,这是不明确的”意味着您的索引是“productID”,并且是一个列,可能在任一数据帧上使用了set_index()作为产品ID,要么重命名索引名称,要么删除相同的列并使用合并的left_index/right_index参数。 - anky
谢谢@anky_91。下面的答案解决了我的问题。 - sylvia
1个回答

4

错误意味着有一个与列productID相同的索引名称:

#check it
print (df2.index.name)

解决方法是删除/重命名索引名称,例如通过DataFrame.rename_axis

pd.merge(df1, df2.rename_axis(None)[['userID','productID', 'usage']], 
          on='productID', how = 'outer')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接