Pandas -获取某些行的小计

8iwquhpp  于 2022-12-16  发布在  其他
关注(0)|答案(2)|浏览(132)

数据框为:

host  status count
0   ast2  0      1
1   ast2  1      2
2   ast2  2      3
3   ast3  0      4
4   ast3  1      5
5   ast3  2      6
6   ast9  0      7
7   ast9  2      8

如何获取状态仅为0或1而非2的行的小计?因此结果应为:

host  status count
0   ast2  0      3
1   ast2  2      3
2   ast3  0      9
3   ast3  2      6
4   ast9  0      7
5   ast9  2      8
gr8qqesn

gr8qqesn1#

您可以将status列的1替换为0,然后聚合sum

df1 = (df.assign(status = df['status'].mask(df['status'].eq(1), 0))
        .groupby(['host','status'], as_index=False)['count']
        .sum())
print (df1)
   host  status  count
0  ast2       0      3
1  ast2       2      3
2  ast3       0      9
3  ast3       2      6
4  ast9       0      7
5  ast9       2      8

字符串
替代解决方案:

df1 = (df.replace({'status':{1:0}})
         .groupby(['host','status'], as_index=False)['count']
         .sum())
tyu7yeag

tyu7yeag2#

result = df[df['status'].isin([0, 1])].groupby('host')['count'].sum()

这将为您提供以下输出:

host
ast2    3
ast3    9
ast9    0

相关问题