简体   繁体   中英

How to Group By and Count total in that group Pandas

Hi I have the following 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

And i am hoping to simply get a total count next to each name so that it becomes:

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

have tried:

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

but get a ValueError: Wrong number of items passed 8, placement implies 1

Any ideas? thanks verymuch!

Use GroupBy.transform with specified column after groupby with aggregate function:

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

If need counts values:

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

You should try this:

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

This will give you the required output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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