测试pandas DataFrame的任何列是否满足条件 [英] Test if any column of a pandas DataFrame satisfies a condition
本文介绍了测试pandas DataFrame的任何列是否满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含很多列的DataFrame.现在,我有一个条件来测试其中某些列,如果该列集中的任何一个都不为零.
I got a DataFrame with lots of columns. Now I have a condition that tests some of those columns if any of that column-set is different to zero.
是否有更优雅的方法将该条件应用于一列列?我当前的代码是:
Is there any more elegant way to apply that condition to a subset of columns? My current code is:
df['indicator'] = (
(df['col_1'] != 0) |
(df['col_2'] != 0) |
(df['col_3'] != 0) |
(df['col_4'] != 0) |
(df['col_5'] != 0)
)
我正在寻找类似这样的伪代码:
I was looking for something like this pseudo code:
columns = ['col_1', 'col_1', 'col_2', 'col_3', 'col_4', 'col_5']
df['indicator'] = df.any(columns, lambda value: value != 0)
推荐答案
ne
是!=
的方法形式.我用它来使流水线any
看起来更好.我使用any(axis=1)
来连续查找是否为真.
ne
is the method form of !=
. I use that so that pipelining any
looks nicer. I use any(axis=1)
to find if any are true in a row.
df['indicator'] = df[columns].ne(0).any(axis=1)
这篇关于测试pandas DataFrame的任何列是否满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文