-2

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

Scope
  • 727
  • 4
  • 15
  • please review and follow the guidelines here: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples and do not paste pandas as images ever, paste them as construction code – piterbarg Feb 02 '22 at 17:17
  • you don't have `chocoalte` but `chcolate` instead (both with typos) –  Feb 02 '22 at 17:18

2 Answers2

2

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])
piterbarg
  • 8,089
  • 2
  • 6
  • 22
1

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')