Skip to content Skip to sidebar Skip to footer

Replace Column Values Within A Groupby And Condition

I have a dataframe that I want to find the minimum value of a column within a group, and then based on that row, update the values of some of the other columns. The following code

Solution 1:

Use groupby on ID + transform + idxmin on Year to get a series of indices. Pass these indices to loc to get your result.

(df.iloc[df.groupby('ID')['Year'].transform('idxmin')]
   .reset_index(drop=True)
   .assign(Albedo=df['Albedo']))

   Albedo  ID  Precip  Temp  Year
0     0.2   1     200    20  1950
1     0.4   1     200    20  1950
2     0.5   1     200    20  1950
3     0.3   2      45     5  1916
4     0.5   2      45     5  1916
5     0.1   2      45     5  1916

Post a Comment for "Replace Column Values Within A Groupby And Condition"