Count number of a value for every line in pandas matrix

Viewed 71

I have a matrix of the form :

movie_id  1     2     3     4  ...   100
user_id                                                             
100      1.0   0.0   1.0   0.0 ...   0.0   
101      1.0   NaN   0.0   NaN ...   NaN   
.        NaN   NaN   NaN   NaN ...   NaN    
.        NaN   0.0   1.0   NaN ...   1.0 
.        1.0   0.0   NaN   NaN ...   NaN    
200      1.0   NaN   NaN   1.0 ...   1.0 

I would like to count the 1s' for a specific user (each line index) in each iteration.

(You could think of the matrix in a form of a dictionary too if that's needed)

1 Answers

Use df.sum(axis=1) if only 0, 1 values.

If your data can contain other values than 0 or 1, you need to create a mask first:

s = df.eq(1).sum(axis=1)
print (s)
user_id
100    2
101    1
103    0
105    2
110    1
200    3
dtype: int64
Related