简体   繁体   English

在给定特定条件的情况下,如何在 pandas dataframe 上使用 .count()?

[英]How can I use .count() on a pandas dataframe given a certain condition?

I have tried both of these:我已经尝试了这两个:

    df["Buys"] = df.groupby(['symbol','month','counterparty','side'])[df[df['side']=='Buy']].count()
    df["Sells"] = df.groupby(['symbol','month','counterparty','side'])[df['side']=='Sell'].count()

But for the first I get the error "DataFrame is not hashable" and for the second "True is not a key".但是第一次我得到错误“DataFrame 不可哈希”,第二次“True 不是一个键”。 What am I doing wrong here?我在这里做错了什么?

Okay, I think I half figured it out.好吧,我想我明白了一半。 I did我做了

dfBuys = df.groupby(['symbol','month'])['side'].apply(lambda x: (x=='Buy').sum()).reset_index(name='count')
df["Buys"] = dfBuys["count"]

dfBuys["count"] is exactly what I'm looking for, but for whatever reason sometimes df["Buys"] doesn't populate, but for the most part it works. dfBuys["count"] 正是我要找的,但无论出于何种原因,有时 df["Buys"] 不会填充,但在大多数情况下它都有效。

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

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