How can I sort a mixed list of integers as repeating numbers with pandas like 1-2-3-4-1-2-3-4…?

0

Issue

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?

[Edited]
@Corralien’s solution helped me.

import pandas as pd
df = pd.read_csv("students.csv", encoding='utf-8')

df['A'] = df['Class']
df = df.assign(B=df.groupby('A').cumcount()).sort_values(['B', 'A']).drop(columns=['A','B'])

print(df.head(20))

Result:

enter image description here

Solution

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

Answered By – Corralien

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More