'Place the first value of Column B in Column C if Column A has same names in python pandas with loop [duplicate]

I have the following data set in python,

Input

enter image description here

I want to bring the first value of Column B that belongs to column Column A for a unique A value to be pasted in Column C.

For eg. value a in Column A has ABC, XYZ, and PQR, so in column C I want ABC, ABC, ABC Similarly for value b in Column A.

Expected Output:

enter image description here

I tried the following code in python.

df['C']=None
for i in range(len(df)):
    if df['A'][i]==df['A'][i+1] and df['C'][i]==None:
        df['C'][i]=df['B'][i]
        if df['A'][i]==df['A'][i+1] and df['C'][i]!=None

I am stuck how to proceed with that. I will be really grateful for any help



Solution 1:[1]

df["C"] = df[df.index.isin(df.reset_index().groupby("A")["index"].first().to_list())]["B"]
df["C"].fillna(method='ffill', inplace=True)

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 Alex