【问题标题】:Pandas dataframes custom ordering熊猫数据框自定义排序
【发布时间】:2021-10-14 21:12:15
【问题描述】:

在一列中,我有 4 个可能的(非顺序)值:A、2、+、?我想根据自定义序列 2、?、A、+ 对行进行排序,我遵循了一些我在网上遵循的代码:

order_by_custom = pd.CategoricalDtype(['2', '?', 'A', '+'], ordered=True)
df['column_name'].astype(order_by_custom)
df.sort_values('column_name', ignore_index=True)

但由于某种原因,虽然它确实进行了排序,但它仍然根据字母(或二进制值)位置而不是我在 order_by_custom 对象中输入它们的顺序进行排序。

有什么想法吗?

【问题讨论】:

  • 您没有重新分配类型更改,因此订单被忽略。那是df['column_name'] = df['column_name'].astype(order_by_custom)

标签: python pandas sorting


【解决方案1】:

.astype 确实在转换后返回系列,但你没有用它做任何事情。尝试将其分配给您的df。考虑以下示例:

import pandas as pd
df = pd.DataFrame({'orderno':[1,2,3],'custom':['X','Y','Z']})
order_by_custom = pd.CategoricalDtype(['Z', 'Y', 'X'], ordered=True)
df['custom'] = df['custom'].astype(order_by_custom)
print(df.sort_values('custom'))

输出

   orderno custom
2        3      Z
1        2      Y
0        1      X

【讨论】:

    【解决方案2】:

    您可以使用自定义字典对其进行排序。例如字典将是:

    my_custom_dict = {'2': 0, '?': 1, 'A': 2, '+' : 3}
    

    如果您的列名是“my_column_name”,那么,

    df.sort_values(by=['my_column_name'], key=lambda x: x.map(my_custom_dict))
    

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 2012-11-30
      • 1970-01-01
      • 2017-08-21
      • 2021-09-27
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多