计算 pandas 行中True/False值的数量 [英] counting the amount of True/False values in a pandas row

查看:356
本文介绍了计算 pandas 行中True/False值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

熊猫中是否有一种方法可以计算一列中有多少个True或False条件.

Is there a way in pandas to calculate how many True or False conditions are there in a column.

例如:如果一个数据框有5列,而我想选择至少3列的行,且这些列的值均大于3,是否可以在不使用迭代器的情况下做到这一点? 因此,在下面的示例中,我将选择行b和c.

eg: If a data frame has 5 columns and I want to select rows with at least three columns with values > 3, can this be done without the use of an iterator? So in the example below i will select rows b and c.

In [12]: df2
Out[12]: 
       A   B  C   D   E
    a  1   2  2   8   6
    b  3   6  5   8   8
    c  6   2  5   5   2

推荐答案

您可以执行以下操作:

df[(df > 3).sum(axis=1) >= 3]

其中,df > 3根据条件返回整个DataFrame上的布尔掩码,而sum(axis=1)返回每一行中该掩码中True的数量.最后,>=3操作返回另一个可用于过滤原始DataFrame的掩码.

where df > 3 returns a Boolean mask over the entire DataFrame according to the condition, and sum(axis=1) returns the number of True in that mask, for each row. Finally the >=3 operation returns another mask that can be used to filter the original DataFrame.

输出:

   A  B  C  D  E
b  3  6  5  8  8
c  6  2  5  5  2

这篇关于计算 pandas 行中True/False值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆