我有一个Excel,其中包含一些数据,如下图所示。如果将A列和B列与D列和E列进行比较(A1,B1存在于D和E中,A3,B3存在于D,E中......)所以这两个为 true,其他为 false,如何用 python 编写代码 我只能看到行比较,现在正在寻找单元格到列的比较,例如(A1,B1 必须比较列 D,E 并通过增加 A2,A3 来重复此操作......
在不知道单元格限制的情况下比较Excel多单元格数据与多列。
我想出了 3 种不同的方法来解决这个问题。我唯一的疑问是您没有突出显示 A & B 和 D & E 中的 10 & 400 的组合。因此我的答案包括了这一点,所以我不确定这是否是您想要的。
df = pd.DataFrame({
'A':[1,2,3,4,5,6,7,8,9,10],
'B':[100,900,300,600,500,900,1000,700,200,400],
'C':[6,2,7,9,3,1,8,10,4,5],
'D':[800,400,1000,100,300,100,600,400,600,500]
})
# Method 1 - this converts column A & B into a tuple and compares to
# a tuple of C & D
df['new_column_1'] = (df[['A', 'B']].apply(tuple, axis=1)
.isin(df[['C', 'D']].apply(tuple, axis=1)))
# Method 2 - this utilizes numpy which can often be faster
df['new_column_2'] = np.any((df['A'].values[:, None] == df['C'].values) & (df['B'].values[:, None] == df['D'].values), axis=1)
# Method 3 - this utilizes pandas merge function
merged_df = df.merge(df, left_on=['A', 'B'], right_on=['C', 'D'], how='left', indicator=True)
df['new_column_3'] = merged_df['_merge'] == 'both'
df