Dennis
Dennis

Reputation: 215

How to sum up rows in a dataframe?

I have created a dataframe df what looks like:

          dates  counts1.22.171.gjj.csv  counts4.16.8.iei.csv  \
0     2003-01-01                       0                     0   
1     2003-01-02                       1                     1   
2     2003-01-03                       0                     0   
3     2003-01-04                       0                     0   
4     2003-01-05                       0                     0   
5     2003-01-06                       1                     0   
6     2003-01-07                       0                     0   
7     2003-01-08                       0                     1  

witch much more rows and columns. I want to sum up the zeros and ones in each row so that I have something like:

          dates  counts  
0     2003-01-01     0                                          
1     2003-01-02     2                                          
2     2003-01-03     0                                        
3     2003-01-04     0                                          
4     2003-01-05     0                                         
5     2003-01-06     1                                      
6     2003-01-07     0                                          
7     2003-01-08     1

I used df.sum(axis=1) and become


0         0                                          
1         2                                          
2         0                                        
3         0                                          
4         0                                         
5         1                                      
6         0                                          
7         1 

How can I become my expected output where I have the dates in the second column and have headliners?

Upvotes: 2

Views: 66

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

In [67]: df.assign(counts_sum=df.sum(axis=1))[["dates","counts_sum"]]
Out[67]:
       dates  counts_sum
0 2003-01-01           0
1 2003-01-02           2
2 2003-01-03           0
3 2003-01-04           0
4 2003-01-05           0
5 2003-01-06           1
6 2003-01-07           0
7 2003-01-08           1

Upvotes: 1

Related Questions