how to replace the values of one column by taking the duplicated values applied on the other column

Viewed 55

so i have a dataframe like

    name    age year
0   ram     25  97
1   syam    12  95
2   jodu    15  96
3   ram     23  98
4   jodu    20  99
5   shyam   18  10

from the dataframe i see that the duplicate names e.g ram or shyam has different ages and different years. i want to raplace all the ages of ram by the lowest value. here 3 rams has 3 ages i.e 25 and 23. i want to fill all the ages of ram with the lowest value between 25 and 23. so my new data will be

    name    age year
0   ram     23  97
1   syam    12  95
2   jodu    15  96
3   ram     23  98
4   jodu    15  99
5   shyam   12  10

how can i do that in pandas?

3 Answers

Try groupby transform:

df = df.assign(age = df.groupby('name')['age'].transform(min)) # here assign will return a new df
# or df.age =  df.groupby('name')['age'].transform(min)) # change on same dataframe

Try this:

df['age'] = df.groupby('name')['age'].transform('min')

Have this(i replaced"name by nam -- because of speedy typing):

for n in range(len(df)):
      name_temp=df.loc[n].nam
      df.replace(df.loc[n].age, ((df.groupby("nam").agg("min").age).to_frame()).loc[name_temp].age, inplace=True)
Related