Home > Blockchain >  Assign pandas dataframe column value based on first ocurrence
Assign pandas dataframe column value based on first ocurrence

Time:02-03

I have a dataframe df1 :-

enter image description here

I want to achieve this transformation in df1:-

enter image description here

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')
  •  Tags:  
  • Related