Maxibond
Maxibond

Reputation: 19

Pandas count values by condition for row

I have a table:

x A B C D
A 1 
B 1 1 1 1  
C 1   1
D

And I want to know a count of 1 in every row. Expected result: { A: 1, B: 4, C: 2, D: 0 }

I tried something df[A][df[A]==1], but it give me same result but by column. I have no idea how to do it.

Upvotes: 0

Views: 6512

Answers (2)

Jan X Marek
Jan X Marek

Reputation: 2504

If the values in the dataframe were numbers (1 or 0), you could use sum by rows:

df = pd.DataFrame([[1,0,0,0],[1,1,1,1],[1,0,1,0],[0,0,0,0]],\
    index=['A','B','C','D'],\
    columns=['A','B','C','D'])

print(df.sum(axis = 1))

A    1
B    4
C    2
D    0
dtype: int64

If they are strings ('1' or '') you can use the same, only the sum operator concatenates them, and then you map them to their lengths.

df = pd.DataFrame([['1','','',''],['1','1','1','1'],['1','','1',''],['','','','']],\
    index=['A','B','C','D'],\
    columns=['A','B','C','D'])

print(df.sum(axis = 1).str.len())

A    1
B    4
C    2
D    0
dtype: int64

Upvotes: 0

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

DataFrame:

In [120]: df
Out[120]:
   A  B  C  D
A  1  7  5  4
B  1  1  1  1
C  1  0  1  9
D  0  2  3  4

Solution:

In [121]: df.eq(1).sum(axis=1).to_dict()
Out[121]: {'A': 1, 'B': 4, 'C': 2, 'D': 0}

Explanation:

In [123]: df.eq(1)
Out[123]:
       A      B      C      D
A   True  False  False  False
B   True   True   True   True
C   True  False   True  False
D  False  False  False  False

In [124]: df.eq(1).sum(axis=1)
Out[124]:
A    1
B    4
C    2
D    0
dtype: int64

Upvotes: 3

Related Questions