英文:
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['col2'] != 0) & (df['col1'] == 0), 'col1'].count() )
Prints:
2
Or:
np.sum( (df['col2'] != 0) & (df['col1'] == 0) )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论