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?
In pandas you can get the count of the frequency of a value that occurs in a DataFrame column by using Series. value_counts() method, alternatively, If you have a SQL background you can also get using groupby() and count() method.
After grouping a DataFrame object on one column, we can apply count() method on the resulting groupby object to get a DataFrame object containing frequency count. This method can be used to count frequencies of objects over single or multiple columns.
To count the frequency of a value in a DataFrame column in Pandas, we can use df. groupby(column name). size() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With