如何使用Pandas按分组计算其他列数值不为零时零值的数量。

huangapple go评论74阅读模式
英文:

How to count how many zero values when other one column values are not zero by groupby pandas

问题

例如,我得到一个dataframe如下所示:

print(df)

    ID    col1    col2
0   0     0       1
1   0     0       0
2   1     1       0
3   1     1       1
4   1     0       1

# 经过一些groupby聚合之后
# 我们计算col2的值为非零时col1零值的数量
    ID    col1
0   0     2

我只知道如何使用groupby pandas来计算dataframe中零值的数量,如下所示:

df.groupby('col1')['col2'].agg(lambda x: x.eq(0).sum())
   ID     col1
0  0      3
1  1      2

所以我想知道如何在使用groupby pandas时计算另一列的值不为零时有多少个零值。
我已经进行了很多搜索,但找不到我想要的。
如果有人能帮助我,那将非常感谢您!

英文:

For example, I get a dataframe as follows:

print(df)

    ID    col1    col2
0   0     0       1
1   0     0       0
2   1     1       0
3   1     1       1
4   1     0       1

# after some groupby aggregations
# we calculate that the count of col1 zero values when col2 values are non-zero 
    ID    col1
0   0     2 

I only know how to count the zero values of a dataframe by groupby pandas like follows:

df.groupby('col1')['col2'].agg(lambda x: x.eq(0).sum())
   ID     col1
0  0      3
1  1      2

So I am wondering how to count how many zero values when other one column values are not zero by groupby pandas.<br>
I have searched a lot but can't find what I want.<br>
If anyone could help me, it will be great thanks to you!

答案1

得分: 1

I'm not sure if I understand you right, but you don't need groupby in this case:

在这种情况下,我不确定我是否理解你的意思,但你不需要使用 groupby

Prints:

打印:

2

Or:

或者:

np.sum( (df['col2'] != 0) & (df['col1'] == 0) )

英文:

I'm not sure if I understand you right, but you don't need groupby in this case:

print( df.loc[(df[&#39;col2&#39;] != 0) &amp; (df[&#39;col1&#39;] == 0), &#39;col1&#39;].count() )

Prints:

2

Or:

np.sum( (df[&#39;col2&#39;] != 0) &amp; (df[&#39;col1&#39;] == 0) )

huangapple
  • 本文由 发表于 2020年1月6日 16:24:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定