【问题标题】:Custom sorting in pandas dataframe熊猫数据框中的自定义排序
【发布时间】:2012-11-30 01:51:13
【问题描述】:

我有 python pandas 数据框,其中一列包含月份名称。

如何使用字典进行自定义排序,例如:

custom_dict = {'March':0, 'April':1, 'Dec':3}  

【问题讨论】:

  • 列是否包含月份名称是否意味着有一列包含月份名称(作为我的回答),或者许多列包含列名称作为月份名称(如 eumiro 的)?
  • 接受的答案已经过时,而且在技术上也不正确,因为pd.Categorical 不会将类别解释为默认排序。见this answer。

标签: python pandas


【解决方案1】:

我有同样的任务,但增加了对多列的排序。

其中一个解决方案是使两列都 pd.Categorical 并将预期顺序作为参数“类别”传递。

但是我有一些要求,我不能强制未知\意外的值,不幸的是,这就是 pd.Categorical 正在做的事情。此外 None 不支持作为一个类别并自动强制。

所以我的解决方案是使用一个键以自定义排序顺序对多个列进行排序:

import pandas as pd


df = pd.DataFrame([
    [A2, 2],
    [B1, 1],
    [A1, 2],
    [A2, 1],
    [B1, 2],
    [A1, 1]], 
  columns=['one','two'])


def custom_sorting(col: pd.Series) -> pd.Series:
    """Series is input and ordered series is expected as output"""
    to_ret = col
    # apply custom sorting only to column one:
    if col.name == "one":
        custom_dict = {}
        # for example ensure that A2 is first, pass items in sorted order here:
        def custom_sort(value):
            return (value[0], int(value[1:]))

        ordered_items = list(col.unique())
        ordered_items.sort(key=custom_sort)
        # apply custom order first:
        for index, item in enumerate(ordered_items):
            custom_dict[item] = index
        to_ret = col.map(custom_dict)
    # default text sorting is about to be applied
    return to_ret


# pass two columns to be sorted
df.sort_values(
    by=["two", "one"],
    ascending=True,
    inplace=True,
    key=custom_sorting,
)

print(df)

输出:

5  A1    1
3  A2    1
1  B1    1
2  A1    2
0  A2    2
4  B1    2

请注意,此解决方案可能会很慢。

【讨论】:

    【解决方案2】:

    更新

    使用selected answer!它比这篇文章更新,不仅是在 pandas 中维护有序数据的官方方法,而且在各个方面都更好,包括功能/性能等。不要使用我在下面描述的 hacky 方法。

    我只是写这个更新,因为人们一直在支持我的答案,但它肯定比接受的更糟糕:)

    原帖

    游戏有点晚了,但这里有一种方法可以创建一个函数,使用任意函数对 pandas Series、DataFrame 和多索引 DataFrame 对象进行排序。

    我使用df.iloc[index] 方法,它按位置引用Series/DataFrame 中的一行(与按值引用的df.loc 相比)。使用它,我们只需要一个返回一系列位置参数的函数:

    def sort_pd(key=None,reverse=False,cmp=None):
        def sorter(series):
            series_list = list(series)
            return [series_list.index(i) 
               for i in sorted(series_list,key=key,reverse=reverse,cmp=cmp)]
        return sorter
    

    您可以使用它来创建自定义排序功能。这适用于安迪·海登回答中使用的数据框:

    df = pd.DataFrame([
        [1, 2, 'March'],
        [5, 6, 'Dec'],
        [3, 4, 'April']], 
      columns=['a','b','m'])
    
    custom_dict = {'March':0, 'April':1, 'Dec':3}
    sort_by_custom_dict = sort_pd(key=custom_dict.get)
    
    In [6]: df.iloc[sort_by_custom_dict(df['m'])]
    Out[6]:
       a  b  m
    0  1  2  March
    2  3  4  April
    1  5  6  Dec
    

    这也适用于多索引 DataFrames 和 Series 对象:

    months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    
    df = pd.DataFrame([
        ['New York','Mar',12714],
        ['New York','Apr',89238],
        ['Atlanta','Jan',8161],
        ['Atlanta','Sep',5885],
      ],columns=['location','month','sales']).set_index(['location','month'])
    
    sort_by_month = sort_pd(key=months.index)
    
    In [10]: df.iloc[sort_by_month(df.index.get_level_values('month'))]
    Out[10]:
                     sales
    location  month  
    Atlanta   Jan    8161
    New York  Mar    12714
              Apr    89238
    Atlanta   Sep    5885
    
    sort_by_last_digit = sort_pd(key=lambda x: x%10)
    
    In [12]: pd.Series(list(df['sales'])).iloc[sort_by_last_digit(df['sales'])]
    Out[12]:
    2    8161
    0   12714
    3    5885
    1   89238
    

    对我来说,这感觉很干净,但它大量使用了 python 操作,而不是依赖于优化的 pandas 操作。我没有进行任何压力测试,但我想这可能会在非常大的 DataFrame 上变慢。不确定性能与添加、排序和删除列相比如何。任何加快代码速度的提示都将不胜感激!

    【讨论】:

    • 这适用于对多个列/索引进行排序吗?
    • 是的,但是选择的答案是更好的方法。如果您有多个索引,只需按照您喜欢的排序顺序排列它们,然后使用df.sort_index() 对所有索引级别进行排序。
    • 分类方法有很多限制。
    【解决方案3】:

    熊猫 >= 1.1

    您很快就能将sort_values 与key 参数一起使用:

    pd.__version__
    # '1.1.0.dev0+2004.g8d10bfb6f'
    
    custom_dict = {'March': 0, 'April': 1, 'Dec': 3} 
    df
    
       a  b      m
    0  1  2  March
    1  5  6    Dec
    2  3  4  April
    
    df.sort_values(by=['m'], key=lambda x: x.map(custom_dict))
    
       a  b      m
    0  1  2  March
    2  3  4  April
    1  5  6    Dec

    key 参数将一个系列作为输入并返回一个系列。这个系列在内部是 argsorted,排序后的索引用于重新排序输入 DataFrame。如果有多个列要排序,键函数将依次应用于每一列。见Sorting with keys。


    熊猫

    一种简单的方法是使用输出Series.map 和Series.argsort 使用DataFrame.iloc 来索引df(因为argsort 产生排序的整数位置);因为你有字典;这变得容易了。

    df.iloc[df['m'].map(custom_dict).argsort()]
    
       a  b      m
    0  1  2  March
    2  3  4  April
    1  5  6    Dec
    

    如果您需要按降序进行排序,请反转映射。

    df.iloc[(-df['m'].map(custom_dict)).argsort()]
    
       a  b      m
    1  5  6    Dec
    2  3  4  April
    0  1  2  March
    

    请注意,这仅适用于数字项目。否则,您将需要使用sort_values 解决此问题,并访问索引:

    df.loc[df['m'].map(custom_dict).sort_values(ascending=False).index]
    
       a  b      m
    1  5  6    Dec
    2  3  4  April
    0  1  2  March
    

    astype(现在已弃用)或pd.Categorical 提供了更多选项,但您需要指定ordered=True 才能使其正常工作。

    # Older version,
    # df['m'].astype('category', 
    #                categories=sorted(custom_dict, key=custom_dict.get), 
    #                ordered=True)
    df['m'] = pd.Categorical(df['m'], 
                             categories=sorted(custom_dict, key=custom_dict.get), 
                             ordered=True)
    

    现在,一个简单的sort_values 电话就可以解决问题:

    df.sort_values('m')
     
       a  b      m
    0  1  2  March
    2  3  4  April
    1  5  6    Dec
    

    groupby 对输出进行排序时也将遵守分类排序。

    【讨论】:

    • 你已经强调过了,但我想重申一下,以防其他人略读并错过它:Pandas Categorical 默认设置为ordered=None。如果不设置,则顺序错误,或者在 V23 上中断。 Max 函数特别给出了一个 TypeError(Categorical 没有为操作 max 排序)。
    【解决方案4】:

    Pandas 0.15 引入了Categorical Series,它提供了一种更清晰的方法:

    首先将月份列设为分类并指定要使用的排序。

    In [21]: df['m'] = pd.Categorical(df['m'], ["March", "April", "Dec"])
    
    In [22]: df  # looks the same!
    Out[22]:
       a  b      m
    0  1  2  March
    1  5  6    Dec
    2  3  4  April
    

    现在,当您对月份列进行排序时,它将根据该列表进行排序:

    In [23]: df.sort_values("m")
    Out[23]:
       a  b      m
    0  1  2  March
    2  3  4  April
    1  5  6    Dec
    

    注意:如果一个值不在列表中,它将被转换为 NaN。


    对那些感兴趣的人来说一个较旧的答案......

    您可以创建一个中间系列,然后set_index:

    df = pd.DataFrame([[1, 2, 'March'],[5, 6, 'Dec'],[3, 4, 'April']], columns=['a','b','m'])
    s = df['m'].apply(lambda x: {'March':0, 'April':1, 'Dec':3}[x])
    s.sort_values()
    
    In [4]: df.set_index(s.index).sort()
    Out[4]: 
       a  b      m
    0  1  2  March
    1  3  4  April
    2  5  6    Dec
    

    如评论所述,在较新的 pandas 中,Series 有一个 replace 方法可以更优雅地执行此操作:

    s = df['m'].replace({'March':0, 'April':1, 'Dec':3})
    

    略有不同的是,如果字典之外有值,则不会引发此问题(它会保持不变)。

    【讨论】:

    • s = df['m'].replace({'March':0, 'April':1, 'Dec':3}) 也适用于第 2 行——只是为了像我这样学习熊猫的人
    • @kdauria 好地方! (自从我写这篇文章以来已经有一段时间了!)替换绝对是最好的选择,另一个是使用.apply({'March':0, 'April':1, 'Dec':3}.get) :) 在 0.15 中,我们将拥有分类系列/列,所以最好的方法是使用它然后排序就可以了.
    • @AndyHayden 我冒昧地用“替换”方法替换了第二行。我希望没关系。
    • @AndyHayden 编辑被拒绝,但我仍然认为这是一个合理的改变。
    • 只要确保你在较新的 pandas 中使用 df.sort_values("m")(而不是 df.sort("m")),否则你会得到一个 AttributeError: 'DataFrame' object has no attribute 'sort' ;)
    【解决方案5】:
    import pandas as pd
    custom_dict = {'March':0,'April':1,'Dec':3}
    
    df = pd.DataFrame(...) # with columns April, March, Dec (probably alphabetically)
    
    df = pd.DataFrame(df, columns=sorted(custom_dict, key=custom_dict.get))
    

    返回包含 March、April、Dec 列的 DataFrame

    【讨论】:

    • 这对实际列进行排序,而不是根据列上的自定义谓词对行进行排序?
    猜你喜欢
    • 2013-10-12
    • 2021-10-14
    • 1970-01-01
    • 2017-08-21
    • 2021-09-27
    • 1970-01-01
    • 2018-07-05
    • 2021-09-17
    相关资源
    最近更新 更多