Pandas 识别是否有任何元素在一行中

Pandas identifying if any element is in a row

我有一个数据框,它是单行数值,我想知道这些值是否大于 2,如果大于 2,则创建一个包含单词 'Diff'[=14 的新列=]

    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() 和其他许多迭代。显然,我的经验不足阻碍了我,google 在这方面无济于事。我尝试的一切都是“系列(或数据框)的真值使用 a.any()、a.all()... 不明确。”任何帮助将不胜感激。

因为只有一行,取dataframe的.max().max()。使用一个 .max(),您将获得每一列的 .max()。第二个 .max() 取所有列的最大值。

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

输出:

    Col_ F_1 F_2 difference
0   1    5   0   Difference

使用 .loc 访问器和 .gt() 查询并同时创建新列并填充它

df.loc[df.gt(2).any(1), "difference"] = 'Difference'

      Col_  F_1  F_2      difference
 0       1    5    0     Difference

除了大卫的回复你还可以试试这个:

if ((df > 2).astype(int)).sum(axis=1).values[0] == 1:
    df['difference']='Difference'