Given a pandas dataframe
df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
'b': [0,0,1,1,2,2,3,3]})
How to sort it along the column b
in such a way that it is rearranged as {0,1,2,3,0,1,2,3}
.
I.e. the resulting dataframe is
1 0
3 1
5 2
7 3
2 0
4 1
6 2
8 3
cumcount
df.assign(x=df.groupby('b').cumcount()).sort_values(['x', 'b']).drop('x', axis=1)
a b
0 1 0
2 3 1
4 5 2
6 7 3
1 2 0
3 4 1
5 6 2
7 8 3
lexsort
, iloc
, and cumcount
df.iloc[np.lexsort([df['b'], df.groupby('b').cumcount()])]
a b
0 1 0
2 3 1
4 5 2
6 7 3
1 2 0
3 4 1
5 6 2
7 8 3
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