![](/img/trans.png)
[英]How to perform a multiple groupby and transform count with a condition in pandas
[英]How to perform a groupby and transform count with a condition in pandas
我有以下 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
然后我嘗試創建額外的列 - 一個顯示按評級分組的嘗試計數(如上所示),然后嘗試做另一個我想計算大於 1 的分數。我試過:
df['scoregreaterthan1'] = df[df.groupby(by=['Rating'])['Score'].transform('count')>1]
我得到一個ValueError: Wrong number of items passed 7, placement implies 1
基本上在上表中,我希望它每列顯示 4 個(4 個分數大於 1)
任何幫助將非常感激! 謝謝
我們應該做
df['scoregreaterthan1'] = df['Score'].gt(1).groupby(df['Rating']).transform('sum')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.