按特定顺序移动 pandas 数据框中的行

Shift rows in pandas dataframe in a specific order

我有一个 pandas 数据框,如下所示:

df = pd.DataFrame({
     'job': ['football','football', 'football', 'basketball', 'basketball', 'basketball', 'hokey', 'hokey', 'hokey', 'football','football', 'football', 'basketball', 'basketball', 'basketball', 'hokey', 'hokey', 'hokey'],
     'team': [4.0,5.0,9.0,2.0,3.0,6.0,1.0,7.0,8.0, 4.0,5.0,9.0,2.0,3.0,6.0,1.0,7.0,8.0],
     'cluster': [0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1]
     })

每个 cluster 包含 9 个团队。每个集群有 3 支球队,每种运动类型 footballbasketballhokey。我想对每个集群应用一个 shift-function,这样团队的顺序就会以一种非常特定的方式出现(我试图用颜色突出显示):

如何为更大的数据框执行此转换(以上述方式移动行)?

让我们使用 groupby + cumcount 创建一个基于列 clusterjob 的顺序计数器,然后使用 sort_values 对数据框进行排序cluster 和这个 counter:

df['j'] = df.groupby(['cluster', 'job']).cumcount()
df = df.sort_values(['cluster', 'j'], ignore_index=True).drop('j', axis=1)

           job  team  cluster
0     football   4.0        0
1   basketball   2.0        0
2        hokey   1.0        0
3     football   5.0        0
4   basketball   3.0        0
5        hokey   7.0        0
6     football   9.0        0
7   basketball   6.0        0
8        hokey   8.0        0
9     football   4.0        1
10  basketball   2.0        1
11       hokey   1.0        1
12    football   5.0        1
13  basketball   3.0        1
14       hokey   7.0        1
15    football   9.0        1
16  basketball   6.0        1
17       hokey   8.0        1