'Assign pandas dataframe column value based on first ocurrence

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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 piterbarg