Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do group by and take Count of one column divide by count of unique of second column of data frame in python pandas?

I have panda data frame with 4 column say 'col1', 'col2', 'col3' and 'col4' now I want to group by col1 and col2 and want to take aggregate say below.

Count(col3)/(Count(unique col4)) As result_col

How do I do this? I am using MySql with pandas.

I have tried many things from the internet but not getting an exact solution, that's why I am posting here. Give reason of downvote so I can improve my question.

like image 916
Mayur Patel Avatar asked Oct 21 '25 07:10

Mayur Patel


1 Answers

It seems you need aggregate by size and nunique and then div output columns:

df = pd.DataFrame({'col1':[1,1,1],
                   'col2':[4,4,6],
                   'col3':[7,7,9],
                   'col4':[3,3,5]})

print (df)
   col1  col2  col3  col4
0     1     4     7     3
1     1     4     7     3
2     1     6     9     5

df1 = df.groupby(['col1','col2']).agg({'col3':'size','col4':'nunique'})
df1['result_col'] = df1['col3'].div(df1['col4'])
print (df1)
           col4  col3  result_col
col1 col2                        
1    4        1     2         2.0
     6        1     1         1.0
like image 56
jezrael Avatar answered Oct 22 '25 22:10

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!