首先,您需要过滤要比较的列。在这种情况下,第 0、1 和 3 列通过执行以下比较 df.iloc[row1,[0, 1, 3]] == df.iloc[row2, [0, 1, 3]]。这将返回 True 或 False 值的数组。但是您需要 all 列相同。要实现这一点,您需要 .all() 方法。只有当数组中的所有值都为 True 时,它才会返回 true。总结:
if (df.iloc[row1,identical_columns] == df.iloc[row2, identical_columns]).all():
而且由于您需要遍历每个可能的行组合,因此双 for 循环会做得很好。
for row1 in range(m-1):
for row2 in range(row1+1, m):
# Check for every row combinaton if the columns are equal
if (df.iloc[row1,identical_columns] == df.iloc[row2, identical_columns]).all():
pass
总共:
import numpy as np
import pandas as pd
df = pd.DataFrame(data=np.random.randint(0, 100, (10, 4)))
m = df.shape[0]
identical_columns = [0, 1, 3]
k = 4
# Force rows values to pass
df.iloc[2, :] = [3, 4, 5, 1]
df.iloc[3, :] = [3, 4, 4, 1]
for row1 in range(m-1):
for row2 in range(row1+1, m):
# Check for every row combinaton if the columns are equal
if (df.iloc[row1,identical_columns] == df.iloc[row2, identical_columns]).all():
if df.iloc[row1,2] - df.iloc[row2,2] <= k:
# TODO: Implement Your logic
print ('We pass!')
else:
print(f"row {row1} and row {row2} don't pass")