I have a dataframe df1 :-
I want to achieve this transformation in df1:-
Wherever chcolate has ocurrence count>1 ,Based on first ocurrence assign the brand the same value
CodePudding user response:
something like this should work where we groupby chcolate and replace the brand with the first element from that group
df['brand'] = df.groupby('chcolate')['brand'].transform(lambda r:r.iloc[0])
CodePudding user response:
try via groupby() transform():
df['brand'] = df.groupby('chcolate')['brand'].transform('first')
OR
If you want orderwise then use sort_values() first then groupby() transform():
df['brand'] = df.sort_values('brand').groupby('chcolate')['brand'].transform('first')


