Giannis
Giannis

Reputation: 83

Change order of values in a column based on values of another column

Let's say that we have the following data frame. For each group of column id, if the order of column y is 'BB' and the next row is 'AA', then I want to change the order of values only on column x and only for this group of id.

id x y
1 10 AA
1 9 AA
2 13 AA
2 19 BB
3 11 BB
3 25 AA

Follows the expected output.

id x y
1 10 AA
1 9 AA
2 13 AA
2 19 BB
3 25 BB
3 11 AA

Upvotes: 2

Views: 88

Answers (1)

piRSquared
piRSquared

Reputation: 294258

argsort

argsort returns the positional slice that would sort your values. So take them and apply it to other values.

df.groupby('id', group_keys=False, as_index=False).apply(
    lambda d: d.assign(x=d.x.to_numpy()[d.y.argsort()])
)

   id   x   y
0   1  10  AA
1   1   9  AA
2   2  13  AA
3   2  19  BB
4   3  25  BB
5   3  11  AA

Upvotes: 3

Related Questions