If a column has duplicates, then how can I set other column values corresponding to the duplicate values same as well? (Pandas)

Viewed 57

I apologize in advance, I don't know how to frame this question properly.

Say we have a Dataframe df,

A B C
pen cat pizza
apple dog taco
pineapple mouse sandwich
pen horse pasta
apple bird biryani

I want it to change as,

A B C
pen cat pizza
apple dog taco
pineapple mouse sandwich
pen cat pizza
apple dog taco

I'm using this logic to do so,

index_dict = dict(df['A'].value_counts())   
temp_index_lst = [key for (key, val) in index_dict.items() if val != 1]
index_lst = []
for index_num in temp_index_lst:
    index_lst.append(list(df.index[df['A'] == index_num]))

for i in range(len(index_lst)):
    b_value = df.loc[index_lst[i][0], 'B']
    c_value = df.loc[index_lst[i][0], 'C']
    
    for j in range(1, len(index_lst[i])):
        df.loc[index_lst[i][j], 'B'] = b_value
        df.loc[index_lst[i][j], 'C'] = c_value

This works fine, but I was wondering if there is a pandas method or a better way to do this (in terms of performance)?

1 Answers

Let us do groupby + transform to broadcast first value across each group

df.assign(**df.groupby('A').transform('first'))

           A      B         C
0        pen    cat     pizza
1      apple    dog      taco
2  pineapple  mouse  sandwich
3        pen    cat     pizza
4      apple    dog      taco
Related