Santoo
Santoo

Reputation: 355

Rearranging or Shuffling Rows Based on Alternative Groups in Pandas

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

Upvotes: 4

Views: 154

Answers (2)

tlentali
tlentali

Reputation: 3455

We can use a cumcount() and a sort_values to do get the expected result :

>>> df["group_cumcounts"] = df.groupby("group").cumcount()
>>> df.sort_values(["group_cumcounts"]).drop("group_cumcounts", axis=1)
    name    value   group
0   a          10   group 1
2   b          20   group 2
4   c          30   group 3
1   d          20   group 1
3   e          10   group 2
5   f          30   group 3

Upvotes: 1

Corralien
Corralien

Reputation: 120429

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')

Upvotes: 4

Related Questions