简体   繁体   中英

Get most common value for each value in row - pandas df

This may be a duplicate please let me know.

I have a pandas df like this:

id name Common
One A
One A
One A
One B
Two C

I'd like to output something like this:

Where the most common name for each id is placed in the common column.

id name Common
One A A
One A A
One A A
One B A
Two C C

I've tried this but at this point i'm throwing darts in the dark

df.groupby(['id', 'name']).agg(lambda x:x.value_counts().index[0])

This works:

df['Common'] = df.groupby('id')['name'].transform(lambda x: x.mode()[0])

Output:

>>> df
    id name Common
0  One    A      A
1  One    A      A
2  One    A      A
3  One    B      A
4  Two    C      C

A longer process is to pivot and map:

df.assign(Common = df.id.map(df.pivot(None, 'id', 'name').mode().T.squeeze()))
 
    id name Common
0  One    A      A
1  One    A      A
2  One    A      A
3  One    B      A
4  Two    C      C

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