Python Pandas Conditional count after groupby -
i have following dataframe:
key1 key2 0 1 one 2 two b 1 3 b 2 4 1 5 c 2
now, want group dataframe key1 , count column key2 value 1 result:
key1 0 2 1 b 1 2 c 0
i usual count with:
df.groupby(['key1']).size()
but dont know how insert condition.
i tryed things this:
df.groupby(['key1']).apply(df[df['key2'] == 'one'])
but dont futher
it great if here
greetings
i think need add condition first:
#if need category c no values of 'one' df11=df.groupby('key1')['key2'].apply(lambda x: (x=='one').sum()).reset_index(name='count') print (df11) key1 count 0 2 1 b 1 2 c 0
or use categorical
key1
, missing value added size
:
df['key1'] = df['key1'].astype('category') df1 = df[df['key2'] == 'one'].groupby(['key1']).size().reset_index(name='count') print (df1) key1 count 0 2 1 b 1 2 c 0
if need combinations:
df2 = df.groupby(['key1', 'key2']).size().reset_index(name='count') print (df2) key1 key2 count 0 1 2 1 2 1 2 b 1 1 3 b 2 1 4 c 2 1 df3 = df.groupby(['key1', 'key2']).size().unstack(fill_value=0) print (df3) key2 1 2 key1 2 1 b 1 1 c 0 1
Comments
Post a Comment