pandas 计算熊猫行中真/假值的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32387524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:51:18  来源:igfitidea点击:

counting the amount of True/False values in a pandas row

python-2.7pandasdataframe

提问by firefly

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

Pandas 有没有办法计算一列中有多少 True 或 False 条件。

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.

例如:如果数据框有 5 列,并且我想选择至少有三列且值 > 3 的行,是否可以在不使用迭代器的情况下完成?所以在下面的例子中,我将选择行 b 和 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

回答by YS-L

You can do this:

你可以这样做:

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

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

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

Output:

输出:

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