Pandas - 获取某些行的小计

标签 pandas dataframe

DataFrame 为:

    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

最佳答案

您可以将 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())

关于Pandas - 获取某些行的小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74798419/

相关文章:

pandas - dtype=datetime64[ns, UTC] 和时间戳之间的无效比较

r - 在 R data.frame 上有效组合多个条件

python - 查找 pandas 中两个数据帧的差异和串联

python - 如何在 Python 中将 JSON post 请求转换为 DataFrame

r - 如何通过列名向量对数据框进行排序?

python - Pandas:检查 json 对象中是否存在 dataframe 列

python - 获取 Pandas 中 boolean 值的索引 - python

python - 同时循环测试和训练集

python - 基于另一列从 pandas 数据框中的列中的每个列表中删除元素

python - Pandas 通过多个正则表达式捕获组创建多个列