以下是一个使用Python pandas库比较两个数据框并循环遍历它们的示例代码:
import pandas as pd
# 创建示例数据框
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'A': [1, 4, 3], 'B': [7, 8, 9]})
# 比较两个数据框并循环遍历它们
for index, row in df1.iterrows():
if row.equals(df2.iloc[index]):
print(f"Row {index} is equal in both dataframes.")
else:
print(f"Row {index} is not equal in both dataframes.")
输出:
Row 0 is equal in both dataframes.
Row 1 is not equal in both dataframes.
Row 2 is equal in both dataframes.
在上面的代码中,我们首先创建了两个示例数据框df1和df2。然后,使用iterrows()
函数循环遍历df1的每一行,并使用equals()
函数比较当前行是否与df2中相应的行相等。根据比较结果,打印不同的输出。