简体   繁体   English

熊猫数据透视表有条件计数

[英]Pandas Pivot Table Conditional Counting

I have a simple dataframe: 我有一个简单的数据帧:

df = pd.DataFrame({'id': ['a','a','a','b','b'],'value':[0,15,20,30,0]})
df
  id  value
0  a      0
1  a     15
2  a     20
3  b     30
4  b      0

And I want a pivot table with the number of values greater than zero. 我想要一个数值大于零的数据透视表。

I tried this: 我试过这个:

raw = pd.pivot_table(df, index='id',values='value',aggfunc=lambda x:len(x>0))

But returned this: 但是回复了这个:

    value
id
a       3
b       2

What I need: 我需要的:

    value
id
a       2
b       1

I read lots of solutions with groupby and filter. 我用groupby和filter阅读了很多解决方案。 Is it possible to achieve this only with pivot_table command? 是否可以使用pivot_table命令实现此目的? If it is not, which is the best approach? 如果不是,哪种方法最好?

Thanks in advance 提前致谢

UPDATE UPDATE

Just to make it clearer why I am avoinding filter solution. 只是为了让我更清楚为什么我要避免使用过滤器解决方案。 In my real and complex df, I have other columns, like this: 在我的真实和复杂的df中,我有其他列,如下所示:

df = pd.DataFrame({'id': ['a','a','a','b','b'],'value':[0,15,20,30,0],'other':[2,3,4,5,6]})
df
  id  other  value
0  a      2      0
1  a      3     15
2  a      4     20
3  b      5     30
4  b      6      0

I need to sum the column 'other', but when i filter I got this: 我需要将列“其他”加起来,但是当我过滤时我得到了这个:

df=df[df['value']>0]
raw = pd.pivot_table(df, index='id',values=['value','other'],aggfunc={'value':len,'other':sum})
    other  value
id
a       7      2
b       5      1

Instead of: 代替:

    other  value
id
a       9      2
b      11      1

Need sum for count True s created by condition x>0 : 需要sum为条件x>0创建的计数True s:

raw = pd.pivot_table(df, index='id',values='value',aggfunc=lambda x:(x>0).sum())
print (raw)
    value
id       
a       2
b       1

As @Wen mentioned, another solution is: 正如@Wen所说,另一个解决方案是:

df = df[df['value'] > 0]
raw = pd.pivot_table(df, index='id',values='value',aggfunc=len)

您可以在透视之前过滤数据帧:

pd.pivot_table(df.loc[df['value']>0], index='id',values='value',aggfunc='count')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM