-1

If I have a dataframe like this:

Area Favorite Fruit
UT Banana
TN Grape
VT Banana
AZ Banana
CA Cherry

I want to insert a column with a count for how many times the fruit appears across the df like so:

Area Favorite Fruit Fruit Count
UT Banana 3
TN Grape 1
VT Banana 3
AZ Banana 3
CA Cherry 1

Trying to do this in python.

rubengavidia0x
  • 501
  • 1
  • 5
  • 18
Devin
  • 363
  • 2
  • 20
  • 1
    Welcome to stack overflow! [please paste data and code snippets in as block text](https://meta.stackoverflow.com/a/285557/3888719), not pictures. images aren't searchable, can't be copied, and for me in this case, I can't see your examples because I'm viewing stack overflow in dark mode. thanks! – Michael Delgado Aug 10 '21 at 01:58

2 Answers2

2

Use transform('size'):

df['Fruit Count'] = df.groupby('Favorite Fruit')['Favorite Fruit'].transform('size')
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

Try with value_counts + reindex

df['Fruit Count'] = df['Favorite Fruit'].value_counts()\
                   .reindex(df['Favorite Fruit']).values
BENY
  • 317,841
  • 20
  • 164
  • 234