首页 > 解决方案 > 检查列值是否大于熊猫列和python变量之间的最大值

问题描述

我有一个看起来像这样的数据框

pd.DataFrame({'A': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7'],
  ...:                    'x': [2, 2, 3, 2, 3, 1, 3],
  ...:                    'maxValue_1': [2, 1, 2, 3, 4, 2, 1]})
Out[7]: 
    A  x  maxValue_1
0  C1  2           2
1  C2  2           1
2  C3  3           2
3  C4  2           3
4  C5  3           4
5  C6  1           2
6  C7  3           1

maxValue_2 = 2

我需要检查列 'x' 是否等于或大于 max(df.maxValue_1, maxValue_2)

生成的数据框应如下所示。

    A  x  maxValue_1  result
0  C1  2           2   True
1  C2  2           1   True
2  C3  3           2   True
3  C4  2           3   False
4  C5  3           4   False
5  C6  1           2   False
6  C7  3           1   True

如何以有效的方式对此进行编码,而无需将变量“maxValue_2”添加到数据框中?

标签: pythonpandas

解决方案


df['result'] = df['x'] >= np.maximum(df['maxValue_1'], maxValue_2)
print(df)

印刷:

    A  x  maxValue_1  result
0  C1  2           2    True
1  C2  2           1    True
2  C3  3           2    True
3  C4  2           3   False
4  C5  3           4   False
5  C6  1           2   False
6  C7  3           1    True

推荐阅读