Mr.Bean
Mr.Bean

Reputation: 77

How to count group by condition in pandas?

My input dataframe name 'df'

enter image description here

I want to create a new dataframe name 'df1' group by 'date' in df, which include 2 fields: 'date' and 'sponsorRate' with calculation formula as below

date = df.date sponsorRate = count(sponsored) on check column / count total on check column

My desired output

enter image description here

Tks for all helps

Upvotes: 2

Views: 47

Answers (1)

jezrael
jezrael

Reputation: 862406

Compare check and aggregate mean:

df1 = df['check'].eq('sponsored').groupby('date').mean().reset_index()

Or:

df1 = df['check'].eq('sponsored').groupby(level=0).mean().reset_index()

Upvotes: 1

Related Questions