Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add calculated column to Dataframe counting frequency in column in pandas

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?

like image 676
data_b77 Avatar asked Feb 05 '19 19:02

data_b77


People also ask

How do you count the frequency of a column in pandas?

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.

How can I get the frequency counts of each item in one or more columns in a DataFrame?

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.

How do you count the frequency of a word in a pandas DataFrame?

To count the frequency of a value in a DataFrame column in Pandas, we can use df. groupby(column name). size() method.


1 Answers

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
like image 98
Vaishali Avatar answered Oct 16 '22 12:10

Vaishali