python - Applying a custom function on Group By if row count greater than 1 -
how apply function dataframe after grouping if want apply function on groups group has membership greater 1.
e.g
df1 = df.groupyby(['x','y']).count() > 1.apply(f) f(x) :
secondly being passed function - elements on group or group itself.
i think need size
:
df1 = df.groupby(['x','y']).size() df1[df1 > 1] = df1[df1 > 1].apply(f)
aggregating size , count - differences.
sample:
df = pd.dataframe({'x':[1,1,3], 'y':[5,5,6], 'c':[7,8,9]}) print (df) c x y 0 7 1 5 1 8 1 5 2 9 3 6 def f(x) : return x + 2
df1 = df.groupby(['x','y']).size() s = df1[df1.count > 1].set_index('x')['y'] print (s) x 1 5 name: y, dtype: int64 mask = df.set_index('x')['y'].isin(s).values print (mask) [ true true false] df[mask] = df[mask].apply(f) print (df) c x y 0 9 3 7 1 10 3 7 2 9 3 6
Comments
Post a Comment