根据系列规则在Pandas数据框中排序数据

时间:2018-09-03 09:02:25

标签: python pandas

首先要有2个快速保龄球,然后是2个微调器,然后是1个快速保龄球和全能球(Batsman + Bowler)。它们的顺序将取决于所取的小门的数量。

     Name             Role            run_scored  wickets_taken
19    P          Fast Bowler          62             13
18    Q          Spin Bowler          65             12
16    O          Fast Bowler          32              9
15    N  Batsman+Fast Bowler         114              8
14    K          Fast Bowler          24              7
13    T          Spin Bowler          17              6

1 个答案:

答案 0 :(得分:1)

您可以按下降的小门排序,创建将Role映射到数据帧切片的字典,然后根据您的规则将结果串联起来。

# sort by 'wickets_taken'
df = df.sort_values('wickets_taken', ascending=False)

# group by 'Role'
g = dict(tuple(df.groupby('Role')))

# concatenate custom slices
res = pd.concat([g['FastBowler'].iloc[:2],
                 g['SpinBowler'],
                 g['FastBowler'].iloc[2:],
                 g['Batsman+FastBowler']],
                ignore_index=True)

结果

print(res)

  Name                Role  run_scored  wickets_taken
0    P          FastBowler          62             13
1    O          FastBowler          32              9
2    Q          SpinBowler          65             12
3    T          SpinBowler          17              6
4    K          FastBowler          24              7
5    N  Batsman+FastBowler         114              8