I have a mixed list of integers from 1 to 4 (for example 100 numbers like this). I want to sort this list like (1-2-3-4-1-2-3-4 .... 1-2-3-4). Is there a simple way I can do this with numpy or pandas?
CodePudding user response:
Create a temporary column to sort your dataframe:
>>> df.assign(B=df.groupby('A').cumcount()).sort_values(['B', 'A']).drop(columns='B')
A
1 1
8 2
3 3
0 4
2 1
9 2
5 3
4 4
11 1
10 2
12 3
6 4
14 1
17 2
13 3
7 4
18 1
19 2
16 3
15 4
Setup:
import pandas as pd
import numpy as np
np.random.seed(2022)
df = pd.DataFrame({'A': [1,2,3,4]*5})
df = df.sample(frac=1).reset_index(drop=True)
print(df)
# Output
A
0 4
1 1
2 1
3 3
4 4
5 3
6 4
7 4
8 2
9 2
10 2
11 1
12 3
13 3
14 1
15 4
16 3
17 2
18 1
19 2
