Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of columns with a value on each row in python?

Tags:

python

pandas

I have a dataframe like this:

IndividualID Trip1 Trip2 Trip3 Trip4 Trip5 Trip6 Trip7 Trip8 Trip9
200100001    23    1     2     4     4      1    5     5     5
200100002    21    1     12    3     1      55   7     7
200100003    12    3     3     6     3     
200100004    4   
200100005    6     5     3     9     3      5    6  
200100005    23    4     4     2     4      3    6     5  

I'm trying to know the number of trips that each individual makes, so I would like to create a new column so the new table would probably look like this:

IndividualID Trip1  Trip2  Trip3  Trip4  Trip5  Trip6  Trip7  Trip8  Trip9 Chains
200100001     23     1      2      4      4      1     5       5     5      9
200100002     21     1      12     3      1      55    7       7            8
200100003     12     3      3      6      3                                 5
200100004     4                                                             1
200100005     6      5      3      9      3      5     6                    7
200100005     23     4      4      2      4      3     6       5            8

Are there any possible solutions? I would really appreciate if someone can help with it! Thanks in advance!

like image 797
Steward Avatar asked Aug 21 '18 00:08

Steward


1 Answers

Use iloc and count, which ignores NaN by default:

df.iloc[:, 1:].count(1)

0    9
1    8
2    5
3    1
4    7
5    8
dtype: int64

If the values are not NaN, just replace the empty string with NaN:

df.iloc[:, 1:].replace('', np.nan).count(1)
like image 140
user3483203 Avatar answered Sep 29 '22 12:09

user3483203