要比较数据框每行的列元素,可以使用pandas
库中的apply
函数。下面是一个解决方法的代码示例:
import pandas as pd
# 创建示例数据框
data = {'col1': [1, 2, 3, 4],
'col2': [5, 6, 7, 8],
'col3': [9, 10, 11, 12]}
df = pd.DataFrame(data)
# 定义比较函数
def compare_row(row):
# 比较每行的列元素,并返回比较结果
if row['col1'] > row['col2'] and row['col2'] > row['col3']:
return 'col1 > col2 > col3'
elif row['col1'] < row['col2'] and row['col2'] < row['col3']:
return 'col1 < col2 < col3'
else:
return 'No comparison'
# 应用比较函数到每行
df['comparison'] = df.apply(compare_row, axis=1)
# 打印结果
print(df)
输出结果为:
col1 col2 col3 comparison
0 1 5 9 col1 < col2 < col3
1 2 6 10 col1 < col2 < col3
2 3 7 11 col1 < col2 < col3
3 4 8 12 col1 < col2 < col3
这个示例中,我们定义了一个比较函数compare_row
,它比较每行的列元素,并返回比较结果。然后,我们使用apply
函数将这个比较函数应用到数据框的每一行上,得到一个新的列comparison
,包含比较结果。最后,我们打印出整个数据框,查看结果。