10

I have dataframe like this:

   county
1     N
2     N
3     C
4     N
5     S
6     N
7     N

and what I'd like to reach is:

    county  frequency
1   N       5
2   N       5
3   C       1
4   N       5
5   S       1
6   N       5
7   N       5

Is there any possibility to add such column directly without any intermediate df. I know that I could create another df with group and size function and merge this two dataframes. Howewer, I wonder if there is any function which enable such solution without any intermediate df but maybe with usage of 'apply' and some function or lamba?

Vaishali
  • 37,545
  • 5
  • 58
  • 86
data_b77
  • 415
  • 6
  • 19
  • 1
    Not quite sure what you mean by without requiring an intermediate `DataFrame`, but seems like you want `.transform`: `df['freq'] = df.groupby('county').county.transform('size')` – ALollz Feb 05 '19 at 19:52

1 Answers1

15

Map the values from value_counts to the column

df['frequency'] = df['county'].map(df['county'].value_counts())

    county  frequency
1   N       5
2   N       5
3   C       1
4   N       5
5   S       1
6   N       5
7   N       5
Vaishali
  • 37,545
  • 5
  • 58
  • 86
  • This worked but caused the following message: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead – Almog Woldenberg May 11 '20 at 20:43
  • @AlmogWoldenberg, The column on which you used map would have been created by copying from another column rather using loc. If you show the code on how your df was generated, I can help troubleshoot – Vaishali May 11 '20 at 20:53