How to compare two rows in pandas (across all columns), and sum the output?

134 Views Asked by At

I have data like this-

    User1  User2  User3  User4  User5  User6  User7  User8
w1      1      1      1      1      0      1      1      1
w2      0      1      0      0      1      1      1      1
w3      0      0      1      1      1      1      1      1
w4      1      1      1      0      0      0      0      1
w5      1      0      1      0      1      1      1      0
w6      1      1      1      1      1      1      1      1

Now what I want to do is compare every two consecutive weeks, and find all cases where the change is 1->0 .

So output for the above data would be something like this-

    Column
w1      n/a    
w2      3   
w3      1
w4      4   
w5      2 
w6      0
2

There are 2 best solutions below

1
On BEST ANSWER

could also do it like this:

(df > df.shift(-1)).sum(axis=1)
0
On

Let say the dataframe name is df, so you can achieve it by

abs(df.diff()).sum(axis=1)