我在这里尝试了所有的解决方案: Pandas "Can only compare identically-labeled DataFrame objects" error
对我不起作用。这就是我所拥有的。我有两个数据框。一组是系统中已经存在的一组财务数据,另一组是系统中可能存在或不存在的一些财务数据。我需要找到差异并添加不存在的内容。
代码如下:
import pandas as pd
import numpy as np
from azure.storage.blob import AppendBlobService, PublicAccess, ContentSettings
from io import StringIO
dataUrl = "http://ichart.finance.yahoo.com/table.csv?s=MSFT"
blobUrlBase = "https://pyjobs.blob.core.windows.net/"
data = pd.read_csv(dataUrl)
abs = AppendBlobService(account_name='pyjobs', account_key='***')
abs.create_container("stocks", public_access = PublicAccess.Container)
abs.append_blob_from_text('stocks', 'msft', data[:25].to_csv(index=False))
existing = pd.read_csv(StringIO(abs.get_blob_to_text('stocks', 'msft').content))
ne = (data != existing).any(1)
失败的代码是最后一行。我正在阅读一篇关于确定数据框之间差异的文章。
我检查了所有列的数据类型,它们看起来是一样的。我还进行了并排输出,我对轴、索引进行了排序,删除了索引等。仍然出现该死的错误。
这里是existing and data第一行的输出
>>> existing[:1]
Date Open High Low Close Volume Adj Close
0 2016-05-27 51.919998 52.32 51.77 52.32 17653700 52.32
>>> data[:1]
Date Open High Low Close Volume Adj Close
0 2016-05-27 51.919998 52.32 51.77 52.32 17653700 52.32
这是我收到的确切错误:
>>> ne = (data != existing).any(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda3\lib\site-packages\pandas\core\ops.py", line 1169, in f
return self._compare_frame(other, func, str_rep)
File "C:\Anaconda3\lib\site-packages\pandas\core\frame.py", line 3571, in _compare_frame
raise ValueError('Can only compare identically-labeled '
ValueError: Can only compare identically-labeled DataFrame objects
最佳答案
为了解决这个问题,您需要比较底层的 numpy 数组。
import pandas as pd
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'], index=['One', 'Two'])
df2 = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'], index=['one', 'two'])
df1.values == df2.values
array([[ True, True],
[ True, True]], dtype=bool)
关于Python Pandas 只比较相同标签的 DataFrame 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557131/