Reputation: 169
I have the following table (x):
Column1 | Column2 |
---|---|
A1 | 23 |
B1 | 44 |
Q2 | 66 |
B5 | 77 |
L3 | 87 |
S1 | 90 |
Q6 | 34 |
W3 | 123 |
H9 | 51 |
K5 | 80 |
R4 | 19 |
N8 | 43 |
I would like to split the table into 4 groups (1,2,3,4) in the same order as another column group. The output should look like the following:
Column1 | Column2 | Groups |
---|---|---|
A1 | 23 | 1 |
B1 | 44 | 1 |
Q2 | 66 | 1 |
B5 | 77 | 2 |
L3 | 87 | 2 |
S1 | 90 | 2 |
Q6 | 34 | 3 |
W3 | 123 | 3 |
H9 | 51 | 3 |
K5 | 80 | 4 |
R4 | 19 | 4 |
N8 | 43 | 4 |
What I tried so far?
n2 = 4 # number of groups
idx = set(x.index // (round(len(x)/n2)))
grp = [i for i in range(1, n2+1)]
x['Groups'] = (x.index // (round(len(x)/n2))).map(dict(zip(idx, grp)))
But that does not work. How do I solve this?
Upvotes: 1
Views: 124
Reputation: 294358
np.arange
df.assign(Groups=np.arange(len(df)) // (len(df) // 4) + 1)
Column1 Column2 Groups
0 A1 23 1
1 B1 44 1
2 Q2 66 1
3 B5 77 2
4 L3 87 2
5 S1 90 2
6 Q6 34 3
7 W3 123 3
8 H9 51 3
9 K5 80 4
10 R4 19 4
11 N8 43 4
Upvotes: 1