Liquidity
Liquidity

Reputation: 625

Pandas: get rows with exactly one 0

Given the df:

foo bar baz
0   0   0
0   5   3
1   0   2
1   6   1  

I want to get only the rows with exactly one 0:

foo bar baz
0   5   3
1   0   2

I know df.loc[df['foo'] == 0] will give me all rows where 0 is in the foo column, but it doesn't compare across the row to make sure there is only one 0. My actual data has many more columns, so I'd love a solution that doesn't involve typing out each column title.

Upvotes: 0

Views: 118

Answers (2)

Caio Belfort
Caio Belfort

Reputation: 555

zero_cells = df.apply(lambda x: x==0, axis=0)
zero_counts = zero_cells.apply(lambda x: x.sum(), axis=1)
zero_counts[zero_counts == 1]


#0    False
#1     True
#2     True
#3    False
#dtype: bool

Upvotes: 1

akuiper
akuiper

Reputation: 214957

You can use df.eq(0).sum(1).eq(1) as the condition:

df[df.eq(0).sum(1).eq(1)]

#   foo  bar  baz
#1    0    5    3
#2    1    0    2

Whether elements are equal to 0:

df.eq(0)
#     foo    bar    baz
#0   True   True   True
#1   True  False  False
#2  False   True  False
#3  False  False  False

Count zeros by row:

df.eq(0).sum(1)
#0    3
#1    1
#2    1
#3    0
#dtype: int64

Check whether each row has only one zero:

df.eq(0).sum(1).eq(1)
#0    False
#1     True
#2     True
#3    False
#dtype: bool

Upvotes: 3

Related Questions