基于两列创建新的条件列[重复]

问题描述 投票:0回答:2

我想创建一个新列(第三列),根据以下条件在其中添加 1 或 0:

  1. 如果第 1 列和第 2 列的值相同,则在第 3 列中输入 1
  2. 如果值不匹配,则使用 0。

有人可以使用 pandas 编写一个代码来执行此操作吗?请问很紧急

我很困惑如何处理这个案子。请帮忙。

python pandas dataframe if-statement analytics
2个回答
0
投票

您可以使用 numpys where 函数,它运行速度很快。

df['matched'] = np.where((df['col1'] == df['col2']), 1, 0)

0
投票

获取

1
0
的替代方法:

df['matched'] = df['col1'].eq(df['col2']).astype(int)
© www.soinside.com 2019 - 2024. All rights reserved.