How to count number of elements in a row greater than zero

Viewed 4239

I need to count the number of values in each row that are greater than zero and store them in a new column

The df bellow:

     team        goals    goals_against    games_in_domestic_league
0   juventus       1           0                      0
1   barcelona      0           1                      1
2    santos        2           1                      2

Should become:

     team        goals    goals_against    games_in_domestic_league   total
0   juventus       1           0                      0                 1
1   barcelona      0           1                      1                 2
2    santos        2           1                      2                 3
2 Answers

First idea is select numeric columns, test if greater like 0 and count Trues by sum:

df['total'] = df.select_dtypes(np.number).gt(0).sum(axis=1)

If want specify columns by list:

cols = ['goals','goals_against','games_in_domestic_league']
df['total'] = df[cols].gt(0).sum(axis=1)

Another alternative is to apply a lambda such that:

df['total'] = df[['goals','goals_against','games_in_domestic_league']].apply(lambda x: (x>0).sum(), axis=1)

desired result:

    team    goals   goals_against   games_in_domestic_league  total
0   juventus    1         0                 0                  1
1   barcelona   0         1                 1                  2
2   santos      2         1                 2                  3
Related