python - Pandas "Can only compare identically-labeled DataFrame objects"错误

标签 python pandas

我正在使用 Pandas 比较加载到两个数据帧(uat、prod)中的两个文件的输出: ...

uat = uat[['Customer Number','Product']]
prod = prod[['Customer Number','Product']]
print uat['Customer Number'] == prod['Customer Number']
print uat['Product'] == prod['Product']
print uat == prod

The first two match exactly:
74357    True
74356    True
Name: Customer Number, dtype: bool
74357    True
74356    True
Name: Product, dtype: bool

对于第三次打印,我收到一个错误: 只能比较具有相同标签的 DataFrame 对象。如果前两个比较好,那么第三个有什么问题?

谢谢

最佳答案

这里有一个小例子来证明这一点(它只适用于 DataFrames,而不是 Series,直到 Pandas 0.19 它适用于两者):

In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])

In [3]: df1 == df2
Exception: Can only compare identically-labeled DataFrame objects

一个解决方案是sort the index首先(注:some functions require sorted indexes):

In [4]: df2.sort_index(inplace=True)

In [5]: df1 == df2
Out[5]: 
      0     1
0  True  True
1  True  True

注意:== 也是 sensitive to the order of columns ,因此您可能必须使用 sort_index(axis=1):

In [11]: df1.sort_index().sort_index(axis=1) == df2.sort_index().sort_index(axis=1)
Out[11]: 
      0     1
0  True  True
1  True  True

注意:这仍然会引发(如果排序后索引/列的标签不同)。

关于python - Pandas "Can only compare identically-labeled DataFrame objects"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18548370/

相关文章:

python - 访问 Shapely MultiPoint 中的各个点

python - Pandas 数据框 : how to select rows where one column-value is like 'values in a list'

python - 在数据帧的新列中返回 TextBlob 正、负或中性分类

python - 从分层 DataFrame 中按最大值选择行

python - 同时处理多个文本文件

python - 在我的 Matplotlib 中不显示时间,只显示日期

python - Django 按通用外键排序

java - 使用java编译python代码

python - 按另一个数据框中的数据排序

python - Pandas 合并(如何 ="inner")结果大于两个数据帧