可以使用python中pandas库来实现比较两列并生成新列的操作。具体步骤如下:
导入pandas库
import pandas as pd
创建DataFrame对象,包含两列需要比较的数据
data = {
'col1': [1, 2, 3, 4, 5],
'col2': [3, 4, 1, 2, 5]
}
df = pd.DataFrame(data)
使用apply方法对每行数据进行比较并生成新列
def compare(row):
if row['col1'] == row['col2']:
return 'True'
else:
return 'False'
df['compare_result'] = df.apply(compare, axis=1)
完整示例代码如下:
import pandas as pd
data = {
'col1': [1, 2, 3, 4, 5],
'col2': [3, 4, 1, 2, 5]
}
df = pd.DataFrame(data)
def compare(row):
if row['col1'] == row['col2']:
return 'True'
else:
return 'False'
df['compare_result'] = df.apply(compare, axis=1)
print(df)
输出结果为:
col1 col2 compare_result 0 1 3 False 1 2 4 False 2 3 1 False 3 4 2 False 4 5 5 True
上一篇:比较两列并计算结果行数
下一篇:比较两列并添加条件