Python GroupBy排序 在分组内按列降序排列

3 人关注

我有一个数据集,有以下几列--ID、旧阶段、新阶段和周期号。 每个ID都有多行(2+),描述了新旧阶段之间的一系列来回;这由周期号详细说明。

我试图按ID对多行进行分组(这很好),但在这个分组中,我想按周期数进行排序。例如,如果ID 1有6个周期,我想把6号周期列在第一位,然后是5、4、3,等等。

grouped2 = df.groupby(['ID', 'Old_Stage', 'New_Stage'], as_index=False)['Cycle_Number'].max().sort_values(['Cycle_Number'], ascending=False)
print(grouped2)

这就是我所尝试的,然而,它只按降序对周期号进行排序,而非within the ID grouping.

当前的数据框架。

|ID |Old Stage   |New Stage   |Cycle Number|
|100|In Progress |Under Review|1
|100|Not Started |In Progress |0
|100|Under Review|Completed   |2
|100|Completed   |In Progress |3

希望的数据框架。

|ID |Old Stage   |New Stage   |Cycle Number|
|100|Completed   |In Progress |3
|   |Under Review|Completed   |2
|   |In Progress |Under Review|1
|   |Not Started |In Progress |0
    
5 个评论
D.L
请提供一个原始数据集和预期输出的例子。
最好创建 DataFrame(...) 的示例数据,这样我们就可以测试它并看到问题。
why do you use ['Cycle_Number'].max() ?
我不知道你想用分组做什么,你可以在分组前先进行分类 - df.sort_values(by=['ID','Cycle'], ascending=[True,False])
你能解释一下为什么 df.sort_values(by=['ID','Cycle'], ascending=[True,False]) 在这里不起作用吗?它应该是正确的。
python
pandas
afedly
afedly
发布于 2022-03-24
1 个回答
Gonçalo Peres
Gonçalo Peres
发布于 2022-09-20
已采纳
0 人赞同

小孔 Jezrael mentioned, using pandas.DataFrame.sort_values 如下所示,应该可以解决OP的问题

df = df.sort_values(by=['ID', 'Cycle Number'], ascending=[True, False])
[Out]:
    ID     Old Stage     New Stage  Cycle Number
3  100     Completed   In Progress             3
2  100  Under Review     Completed             2
0  100   In Progress  Under Review             1
1  100   Not Started   In Progress             0

However, OP mentioned

It doesn't keep it grouped by ID

It seems that OP is referring to the order of the index. 如one can see on the output of the previous dataframe, it goes from 3, to 2, to 0, to 1, and, IIUC, OP wants it going from 0 to 1, to 2,和so on.

如果是这样的话,缺少的只是.reset_index(drop=True),如下所示

df = df.sort_values(by=['ID', 'Cycle Number'], ascending=[True, False]).reset_index(drop=True)
[Out]:
    ID     Old Stage     New Stage  Cycle Number