首页 > 解决方案 > 熊猫识别是否有任何元素在一行中

问题描述

我有一个数据框,它是单行数值,我想知道这些值中的任何一个是否大于 2,如果是,则创建一个带有单词“Diff”的新列

    Col_,F_1,F_2
    1,5,0

我的数据框是 diff_df。这是我尝试过的一件事

    c = diff_df >2
    if c.any():
        diff_df['difference']='Difference'

如果我要打印 c。这将是

    Col_,F_1,F_2
    False,True,False 

我已经尝试过 c.all() 和许多其他东西的迭代。显然,我的经验不足让我退缩了,谷歌在这方面没有帮助。我尝试的一切都是“系列(或数据框)的真值使用 a.any()、a.all().... 不明确。”任何帮助将不胜感激。

标签: pandasboolean

解决方案


Since it is only one row, take the .max().max() of the dataframe. With one .max() you are going to get the .max() of each column. The second .max() takes the max of all the columns.

if diff_df.max().max() > 2: diff_df['difference']='Difference'

output:

    Col_ F_1 F_2 difference
0   1    5   0   Difference

推荐阅读