I would like to reorder rows based on group
My current dataframe -
name value group
a 10 group 1
d 20 group 1
b 20 group 2
e 10 group 2
c 30 group 3
f 30 group 3
I want output as reordering rows based on Alternating Groups
name value group
a 10 group 1
b 20 group 2
c 30 group 3
d 20 group 1
e 10 group 2
f 30 group 3
Use groupby_cumcount:
>>> df.assign(rank=df.groupby('group').cumcount()).sort_values('rank')
name value group rank
0 a 10 group 1 0
2 b 20 group 2 0
4 c 30 group 3 0
1 d 20 group 1 1
3 e 10 group 2 1
5 f 30 group 3 1
Obviously, you can drop the column rank by appending .drop(columns='rank')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With