【问题标题】:Pandas column sort within a group, ignoring other columnsPandas 列在组内排序,忽略其他列
【发布时间】:2019-11-28 20:39:58
【问题描述】:

我必须按分组变量 id 对 pandas df 中的列进行排序。排序不会改变任何其他变量的顺序,除了它自己的(sq3)。

我的数据看起来像

index id sq1 sq2 sq3
0   0   0   0   0
1   0   0   1   1
2   0   0   2   2
3   0   0   3   3
4   0   0   5   5
5   0   0   4   4
6   0   0   6   6
7   0   0   7   7
8   0   0   8   8
9   0   0   9   9

我想实现

index id sq1 sq2 sq3
0   0   0   0   0
1   0   0   1   1
2   0   0   2   2
3   0   0   3   3
4   0   0   5   4
5   0   0   4   5
6   0   0   6   6
7   0   0   7   7
8   0   0   8   8
9   0   0   9   9

我尝试了以下有效的代码,但需要很长时间。 任何改进将不胜感激!

df_groups = df.groupby(['id','sq1'])

for name,group in df_groups:
df_groups.apply(lambda x: x['sq3'].sort_values(ascending=False).values)

【问题讨论】:

  • 您可以将它传递给一个 numpy 数组,在那里对其进行排序,然后将其重新分配回 pandas 列? (假设您只是按该单列排序)一些示例数据和输出会很好。
  • 为什么不直接:df_groups = df.sort_values(['id', 'sq1', 'sq3'], ascending=False).set_index(['id', 'sq1'])
  • @PMende - 这对我的目的不起作用。我正在将 sq2 复制到 sq3 中,并希望对 sq3 进行独立排序以查看断点。让我更新一些数据点
  • @qqplot 我想你可能误解了你的操作意味着什么。 Groupby-sorting 实际上与按所有 3 排序相同。

标签: python pandas sorting group-by


【解决方案1】:

transform

df.groupby(['id','sq1']).sq3.transform(sorted)

演示

df.assign(sq3=df.groupby(['id','sq1']).sq3.transform(sorted))

       id  sq1  sq2  sq3
index                   
0       0    0    0    0
1       0    0    1    1
2       0    0    2    2
3       0    0    3    3
4       0    0    5    4
5       0    0    4    5
6       0    0    6    6
7       0    0    7    7
8       0    0    8    8
9       0    0    9    9

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 2021-10-31
    • 1970-01-01
    • 2017-04-15
    • 2023-04-08
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多