How to perform a groupby and transform count with a condition in pandas

邮差的信 提交于 2021-02-11 12:29:06

问题


I have the following dataframe:

# Import pandas library 
import pandas as pd
import numpy as np

# data
data = [['tom', 10,2,'c',100,'x'], ['tom',16 ,3,'a',100,'x'], ['tom', 22,2,'a',100,'x'],
        ['matt', 10,1,'c',100,'x'], ['matt', 15,5,'b',100,'x'], ['matt', 14,1,'b',100,'x']]

# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category','Rating','Other'])
df['AttemptsbyRating'] = df.groupby(by=['Rating'])['Attempts'].transform('count')
df

And i am then trying to create to extra columns - one showing the count of Attempts grouped by rating (as shown above works) and then trying to do another where i want to count scores greater than 1. I have tried:

df['scoregreaterthan1'] = df[df.groupby(by=['Rating'])['Score'].transform('count')>1]

And i am getting a ValueError: Wrong number of items passed 7, placement implies 1

Basically in the table above i am hoping for it to show 4 for every column (4 scores greater than 1)

Any help would be much appreciated! Thanks


回答1:


We should do

df['scoregreaterthan1'] = df['Score'].gt(1).groupby(df['Rating']).transform('sum')


来源:https://stackoverflow.com/questions/62845097/how-to-perform-a-groupby-and-transform-count-with-a-condition-in-pandas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!