Pandas 数据帧equals()方法

原文:https://www.studytonight.com/pandas/pandas-dataframe-equals-method

在本教程中,我们将学习 PandasDataFrame.equals() 。它测试两个对象是否包含相同的元素。该方法允许将两个序列或数据帧相互比较,以查看它们是否具有相同的形状和元素。同一地点的南航被认为是平等的。如果两个对象中的所有元素都相同,则返回boolTrue,否则返回False

  • 行/列索引不需要具有相同的类型,只要这些值被认为是相等的。
  • 相应的列必须是相同的数据类型。

下图显示了DataFrame.equals()方法的语法。

句法

DataFrame.equals(other)

因素

其他:序列或数据帧。要与第一个序列或数据帧进行比较的另一个序列或数据帧。

示例 1:DataFrame.equals()方法

这里,数据帧df1df2的元素和列标签具有相同的类型和值,这将返回True

import pandas as pd
df1 = pd.DataFrame({"col_1": [10,20], "col_2": [20,30]})
print("----The First DataFrame is-----")
print(df1)
df2 = pd.DataFrame({"col_1": [10,20], "col_2": [20,30]})
print("----The second DataFrame is-----")
print(df2)
print("Are the elements in two DataFrame contains same elements:",df1.equals(df2))

一旦我们运行该程序,我们将获得以下输出。

-第一个数据帧是- col 1 col 2 0 10 20 1 20 30 -第二个数据帧是- col 1 col 2 0 10 20 1 20 30 两个数据帧中的元素是否包含相同的元素:真

示例 2:DataFrame.equals()方法

下面的例子与前面的例子相似。由空值和同一位置的空值组成的数据帧df1df2被视为相等。

import pandas as pd
df1 = pd.DataFrame({"col_1": [10,None], "col_2": [20,30]})
print("----The First DataFrame is-----")
print(df1)
df2 = pd.DataFrame({"col_1": [10,None], "col_2": [20,30]})
print("----The second DataFrame is-----")
print(df2)
print("Are the elements in two DataFrame contains same elements:",df1.equals(df2))

一旦我们运行该程序,我们将获得以下输出。

-第一个数据帧是- col 1 col 2 0 10.0 20 1 NaN 30 -第二个数据帧是- col 1 col 2 0 10.0 20 1 NaN 30 两个数据帧中的元素是否包含相同的元素:True

示例 3:DataFrame.equals()方法

数据帧df1df2对于其元素的相同值具有不同的类型,并且将返回False,即使它们的列标签是相同的值和类型。

import pandas as pd
df1 = pd.DataFrame({"col_1": [10.0,20.0], "col_2": [20.0,30.0]})
print("----The First DataFrame is-----")
print(df1)
df2 = pd.DataFrame({"col_1": [10,20], "col_2": [20,30]})
print("----The second DataFrame is-----")
print(df2)
print("Are the elements in two DataFrame contains same elements:",df1.equals(df2))

一旦我们运行该程序,我们将获得以下输出。

-第一个数据帧是- col 1 col 2 0 10.0 20.0 1 20.0 30.0 -第二个数据帧是- col 1 col 2 0 10 20 1 20 30 两个数据帧中的元素是否包含相同的元素:False

结论

在本教程中,我们学习了 PandasDataFrame.equals() 方法。我们通过将该方法应用于两个不同的数据帧来解决不同的例子。