Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

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

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this:

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

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.

Output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...