如何在Python中比较DataFrame每行所有值并生成判断列
解决方案
你可以通过以下步骤实现需求:
核心逻辑:判断每行最大值与第二大值的差值是否大于10——因为第二大值是该行除最大值外最接近最大值的数,只要这个差值大于10,说明最大值和该行所有其他值的差值都大于10;反之则至少有一个值与最大值的差值不超过10。
代码实现:
import pandas as pd # 创建原始DataFrame df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6], 'b': [8, 18, 27, 20, 33, 49], 'c': [2, 24, 6, 16, 20, 52] }) # 新增res列 df['res'] = df.apply( lambda row: 'yes' if (row.max() - row.nlargest(2).iloc[1]) > 10 else 'not', axis=1 ) print(df)
- 输出结果:
a b c res 0 1 8 2 not 1 2 18 24 not 2 3 27 6 yes 3 4 20 16 not 4 5 33 20 yes 5 6 49 52 not
补充说明
row.nlargest(2).iloc[1]用于获取每行的第二大值:先提取该行前两大的数值,再取索引为1的元素(即第二大值)。- 这种方式比遍历每行所有元素更高效,尤其适用于列数较多的场景。
内容的提问来源于stack exchange,提问作者gcicceri
相关产品推荐
相关产品推荐

