Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
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])
over 4 years ago · Santiago Trujillo
2 answers
Answer question

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
over 4 years ago · Santiago Trujillo Report

0

A longer (potentially slower) 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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!