首页 > 解决方案 > 比较行 pandas 值并查看它们是否匹配 python

问题描述

我需要在 pandas 数据框中的行值之间进行一些比较,看看它们是否匹配以及是否不匹配。如果它们匹配,我需要打印出来并确定,如果它们不匹配,我需要打印出完整的行值给用户进行验证。没有模式来决定与哪个值进行比较是正确的,如果只有一个行值与其他行值不匹配,它只需要打印出这些值。

Data:
      df1      df2      df3
  A   6004     6004     6004
  B   1501     1401     1502
  C   200      200      200
  D   101      110      102

Expected output:
The values from A in all datafrafames are correct.
The values from C in all dataframes are correct.

The values from B are:
1501 in df1, 1401 in df2, 1502 in df3
Check your data before compare.

The values from D are:
101 in df1, 110 in df2, 102 in df3
Check your data before compare.

有一个大数据框,我需要打印出所有正确和错误,所以我需要尽可能快,我希望它是一个函数。谢谢。

标签: pythonpandas

解决方案


iterrows使用and非常简单iteritems

for idx, row in df.iterrows():
    if row.nunique()==1: 
        print(f'The values from {idx} in all datarfames are correct')
    else:
        print(f'The values from {idx} are:')
        print(', '.join(f'{v} in {c}' for v,c in row.iteritems()))
        print('Check your data before compare')
    print()

输出:

The values from A in all datarfames are correct

The values from B are:
df1 in 1501, df2 in 1401, df3 in 1502
Check your data before compare

推荐阅读