Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas: Add a column to my dataframe that counts a variable

I have a dataframe 'gt' like this:

org     group org1      1 org2      1 org3      2 org4      3 org5      3 org6      3 

and I would like to add column 'count' to gt dataframe to counts number member of the groups, expected results like this:

org     group   count org1      1       2 org2      1       2 org3      2       1 org4      3       3 org5      3       3 org6      3       3 

I know how to do it per one item of the group, but do not know how to make the count repeated for all of the group items, here is the code I have used:

gtcounts = gt.groupby('group').count() 

Can anybody help?

like image 344
UserYmY Avatar asked Apr 22 '15 08:04

UserYmY


People also ask

How do I add a count to a column in a data frame?

Using DataFrame.transform('count') to add a new column containing the groups counts into the DataFrame.

How do you add a column to a value in a DataFrame Python?

You can use the assign() function to add a new column to the end of a pandas DataFrame: df = df. assign(col_name=[value1, value2, value3, ...])

How do you count specific values in a DataFrame column?

Use Sum Function to Count Specific Values in a Column in a Dataframe. We can use the sum() function on a specified column to count values equal to a set condition, in this case we use == to get just rows equal to our specific data point. If we wanted to count specific values that match another boolean operation we can.

How do you count occurring value in Pandas?

How do you Count the Number of Occurrences in a data frame? To count the number of occurrences in e.g. a column in a dataframe you can use Pandas value_counts() method. For example, if you type df['condition']. value_counts() you will get the frequency of each unique value in the column “condition”.


1 Answers

Call transform this will return a Series aligned with the original df:

In [223]:  df['count'] = df.groupby('group')['group'].transform('count') df Out[223]:     org  group  count 0  org1      1      2 1  org2      1      2 2  org3      2      1 3  org4      3      3 4  org5      3      3 5  org6      3      3 
like image 80
EdChum Avatar answered Sep 27 '22 18:09

EdChum