如何计算行中大于零的元素数

2024-09-28 21:49:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算每行中大于零的值的数量,并将它们存储在一个新列中

df波纹管如下所示:

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

应成为:

     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

Tags: indf数量gamesteamtotalagainstgoals
2条回答

另一种选择是应用lambda,以便:

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

预期结果:

    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

第一个想法是选择数字列,测试是否更大,如0,并按sum计数True

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

如果要按列表指定列,请执行以下操作:

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

相关问题 更多 >