如何将熊猫分组并按总数计算

时间:2020-06-22 13:14:15

标签: python pandas

嗨,我有以下DataFrame:

# Import pandas library 
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
# initialize list of lists 
data = [['tom', 10,1], ['nick', 15,0], ['tom', 14,1], ['jason', 15,0], ['nick', 18,1], ['jason', 15,0], ['jason', 17,1]
       , ['tom', 14,0], ['nick',16 ,1], ['tom', 22,1]] 
  
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Target']) 

# print dataframe. 
df 
Name    Attempts    Target
0   tom     10       1
1   nick    15       0
2   tom     14       1
3   jason   15       0
4   nick    18       1
5   jason   15       0
6   jason   17       1
7   tom     14       0
8   nick    16       1
9   tom     22       1

我希望在每个名称旁边简单地增加一个总数,以便它变为:

Name    Attempts    Target    totalentries
0   tom     10       1             4
1   nick    15       0             3
2   tom     14       1             4
3   jason   15       0             3
4   nick    18       1             3
5   jason   15       0             3
6   jason   17       1             3
7   tom     14       0             4
8   nick    16       1             3
9   tom     22       1             4

尝试过:

df['totalentries'] = df.groupby('Name').nunique()

但是得到一个ValueError: Wrong number of items passed 8, placement implies 1

有什么想法吗?非常感谢!

2 个答案:

答案 0 :(得分:2)

groupby后面的指定列与GroupBy.transform配合使用:

df['totalentries'] = df.groupby('Name')['Target'].transform('nunique')

如果需要计算值:

df['totalentries'] = df.groupby('Name')['Target'].transform('size')

答案 1 :(得分:1)

您应该尝试以下操作:

df["totalentries"] = [df.groupby("Name")["Name"].count()[i] for i in df["Name"].values] 

这将为您提供所需的输出。