pandas 如何忽略熊猫的索引比较断言帧相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51655623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:52:38  来源:igfitidea点击:

how to ignore index comparison for pandas assert frame equal

pythonpandas

提问by Lisa

I try to compare below two dataframe with "check_index_type" set to False. According to the documentation, if it set to False, it shouldn't "check the Index class, dtype and inferred_type are identical". Did I misunderstood the documentation? how to compare ignoring the index and return True for below test?

我尝试将“check_index_type”设置为 False 的两个数据框进行比较。根据文档,如果设置为 False,则不应“检查索引类,dtype 和 inferred_type 是否相同”。我误解了文档吗?如何比较忽略索引并为下面的测试返回 True?

I know I can reset the index but prefer not to.

我知道我可以重置索引但不想这样做。

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.testing.assert_frame_equal.html

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.testing.assert_frame_equal.html

from pandas.util.testing import assert_frame_equal
import pandas as pd
d1 = pd.DataFrame([[1,2], [10, 20]], index=[0,2])
d2 = pd.DataFrame([[1, 2], [10, 20]], index=[0, 1])
assert_frame_equal(d1, d2, check_index_type=False)


AssertionError: DataFrame.index are different
DataFrame.index values are different (50.0 %)
[left]:  Int64Index([0, 2], dtype='int64')
[right]: Int64Index([0, 1], dtype='int64')

回答by YOBEN_S

Index is part of data frame , if the index are different , we should say the dataframes are different , even the value of dfs are same , so , if you want to check the value , using array_equalfrom numpy

索引是数据帧的一部分,如果索引不同,我们应该说数据帧是不同的,甚至dfs的值也一样,所以,如果你想检查值,使用array_equalfrom 。numpy

d1 = pd.DataFrame([[1,2], [10, 20]], index=[0,2])
d2 = pd.DataFrame([[1, 2], [10, 20]], index=[0, 1])
np.array_equal(d1.values,d2.values)
Out[759]: True

For more info about assert_frame_equalin git

有关assert_frame_equalgit 中的更多信息

回答by The Aelfinn

If you really don't care about the index being equal, you can drop the index as follows:

如果您真的不关心索引是否相等,则可以按如下方式删除索引:

assert_frame_equal(d1.reset_index(drop=True), d2.reset_index(drop=True))