How to adress the row with minimum value of the column

Viewed 34

this is the code used for creating the df:

team = np.array(['Ferrari', 'Ferrari', 'Ferrari', 'Ferrari', 'Ferrari', 'Ferrari', 'Ferrari', 'Ferrari'])
year = np.array([2019, 2019, 2019, 2020, 2020, 2020, 2020, 2020])
roundn = np.array([4, 5, 6, 1, 2, 3, 4, 5])
points = np.array([6, 10, 14, 20, 40, 60, 80, 100])

df = pd.DataFrame(team, columns=["team"])
df['year'] = year
df['roundn'] = roundn
df['points'] = points

df = df.groupby(["team", 'year']).apply(display)

enter image description here

So for every group I would like to add the new column that for the minimum value of the roundn column is 1 and else is 0.

I tried something like this but it does not work:

df['new_col'] = np.where(np.argmin(df['roundn']), 1, 0)

Do you have any ideas how to make it work? Thank you in advance.

1 Answers

This produces a single new DataFrame:

df.loc[df.groupby(['team', 'year'])['roundn'].idxmin(), 'new_col'] = 1
df['new_col'].fillna(0, inplace=True)

Alternatively, you can also add a new column per group and combine later with pd.concat

groups = []
for n, g in df.groupby(['team', 'year']):
    g['new_col'] = np.where(g.roundn.min()==g.roundn, 1, 0)
    groups.append(g)

pd.concat(groups)
Related