python - Pandas 分组排序

标签 python pandas sorting pandas-groupby

我想在另一个数组中定义的组边界内对数组进行排序。这些组不会以任何方式进行预排序,并且需要在排序后保持不变。在 numpy 术语中,它看起来像这样:

import numpy as np

def groupwise_sort(group_idx, a, reverse=False):
    sortidx = np.lexsort((-a if reverse else a, group_idx))
    # Reverse sorting back to into grouped order, but preserving groupwise sorting
    revidx = np.argsort(np.argsort(group_idx, kind='mergesort'), kind='mergesort')
    return a[sortidx][revidx]

group_idx =   np.array([3, 2, 3, 2, 2, 1, 2, 1, 1])
a =           np.array([3, 2, 1, 7, 4, 5, 5, 9, 1])
groupwise_sort(group_idx, a)
# >>>            array([1, 2, 3, 4, 5, 1, 7, 5, 9])
groupwise_sort(group_idx, a, reverse=True)
# >>>            array([3, 7, 1, 5, 4, 9, 2, 5, 1])

我怎样才能对 pandas 做同样的事情?我看到了 df.groupby()df.sort_values(),但我找不到实现相同排序的直接方法。如果可能的话,一个快速的。

最佳答案

让我们先搭建舞台:

import pandas as pd
import numpy as np

group_idx =   np.array([3, 2, 3, 2, 2, 1, 2, 1, 1])
a =           np.array([3, 2, 1, 7, 4, 5, 5, 9, 1])

df = pd.DataFrame({'group': group_idx, 'values': a})
df
#   group  values
#0      3       3
#1      2       2
#2      3       1
#3      2       7
#4      2       4
#5      1       5
#6      2       5
#7      1       9
#8      1       1

获取按组和值(组内)排序的数据框:

df.sort_values(["group", "values"])

#   group  values
#8      1       1
#5      1       5
#7      1       9
#1      2       2
#4      2       4
#6      2       5
#3      2       7
#2      3       1
#0      3       3

要按降序对值进行排序,请使用 ascending = False。要对不同的列应用不同的顺序,您可以提供一个列表:

df.sort_values(["group", "values"], ascending = [True, False])

#   group  values
#7      1       9
#5      1       5
#8      1       1
#3      2       7
#6      2       5
#4      2       4
#1      2       2
#0      3       3
#2      3       1

此处,组按升序排序,每个组内的值按降序排序。

要仅对属于同一组的连续行的值进行排序,请创建一个新的组指示符:

(我把它留在这里以供引用,因为它可能对其他人有帮助。在 OP 在评论中澄清他的问题之前,我在早期版本中写了这个。)

df['new_grp'] = (df.group.diff(1) != 0).astype('int').cumsum()
df
#   group  values  new_grp
#0      3       3        1
#1      2       2        2
#2      3       1        3
#3      2       7        4
#4      2       4        4
#5      1       5        5
#6      2       5        6
#7      1       9        7
#8      1       1        7

然后我们可以轻松地使用 new_grp 而不是 group 进行排序,而不会改变组的原始顺序。

在组内排序但保持组指定的行位置:

要对每个组的元素进行排序但保留数据框中特定于组的位置,我们需要跟踪原始行号。例如,以下内容可以解决问题:

# First, create an indicator for the original row-number:

df["ind"] = range(len(df))

# Now, sort the dataframe as before
df_sorted = df.sort_values(["group", "values"])

# sort the original row-numbers within each group
newindex = df.groupby("group").apply(lambda x: x.sort_values(["ind"]))["ind"].values

# assign the sorted row-numbers to the sorted dataframe
df_sorted["ind"] = newindex

# Sort based on the row-numbers:
sorted_asc = df_sorted.sort_values("ind")

# compare the resulting order of values with your desired output:
np.array(sorted_asc["values"])
# array([1, 2, 3, 4, 5, 1, 7, 5, 9])

在函数中编写时,这更容易测试和分析,所以让我们这样做:

def sort_my_frame(frame, groupcol = "group", valcol = "values", asc = True):

    frame["ind"] = range(len(frame))
    frame_sorted = frame.sort_values([groupcol, valcol], ascending = [True, asc])
    ind_sorted = frame.groupby(groupcol).apply(lambda x: x.sort_values(["ind"]))["ind"].values
    frame_sorted["ind"] = ind_sorted
    frame_sorted = frame_sorted.sort_values(["ind"])

    return(frame_sorted.drop(columns = "ind"))

np.array(sort_my_frame(df, "group", "values", asc = True)["values"])
# array([1, 2, 3, 4, 5, 1, 7, 5, 9])
np.array(sort_my_frame(df, "group", "values", asc = False)["values"])
# array([3, 7, 1, 5, 4, 9, 2, 5, 1])

请注意,后者的结果与您想要的结果相符。

我相信这可以用更简洁的方式写出来。例如,如果您的 dataframe 的索引已经排序,您可以使用它来代替我创建的指标 ind (即,在@DJK 的评论之后,我们可以使用sort_index 而不是 sort_values 并避免分配额外的列)。无论如何,以上内容强调了一种可能的解决方案以及如何实现它。另一种方法是使用您的 numpy 函数并将输出包装在 pd.DataFrame 周围。

关于python - Pandas 分组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968316/

相关文章:

python - 比较两个以不同方式缩放或以不同方式压缩的相似图像

python - 对数据框的交替列求和

python - 将列添加到数据透视表( Pandas )

python - 在数据框中另一列的末尾添加现有列

algorithm - 未排序数组中的最大间隙

javascript - 如何使用 underscore.js 根据多个键进行排序?

sql - 如何使用 string_agg 对转换后的字段进行排序

python - 键错误 : None of [Int64Index. ..] dtype='int64] 在列中

c# - 通过 C# 客户端连接到 Python 服务器

python pandas 滚动函数在分组的 DataFrame 中有两个参数