How to customize sorting for pandas dataframe

customize sorting pandas dataframe

author |B. Chen compile |VK source |Towards Data Science

Pandas DataFrame There's a built-in method sort_values(), You can sort values according to a given variable . The method itself is quite simple to use , But it doesn't work with custom sort , for example ,

  • t T-shirt size :XS、S、M、L and XL

  • month : January 、 February 、 March 、 April, etc

  • What day : Monday 、 Tuesday 、 Wednesday 、 Thursday 、 Friday 、 Saturday and Sunday .

In this paper , We will learn how to deal with Pandas DataFrame Custom sort .

Please check my Github repo To get the source code :


Suppose we have a data set about clothing stores :

df = pd.DataFrame({
'cloth_id': [1001, 1002, 1003, 1004, 1005, 1006],
'size': ['S', 'XL', 'M', 'XS', 'L', 'S'],

We can see , Each piece of cloth has a size value , The data should be sorted in the following order :

  • XS For extra large

  • S For Trumpet

  • M For medium

  • L For big

  • XL For extra large

however , When calling sort_values('size') when , You will get the following output .

The output is not what we want , But it's technically correct . actually ,sort_values() It is to sort numerical data in numerical order , Sort the object data in alphabetical order .

Here are two common solutions :

  1. Create a new column for a custom sort

  2. Use CategoricalDtype Cast data to an ordered category type

Create a new column for a custom sort

In this solution , A mapping data frame is needed to represent a custom sort , Then create a new column from the map , Finally, we can sort the data by new columns . Let's take an example to see how this works .

First , Let's create a mapping data frame to represent a custom sort .

df_mapping = pd.DataFrame({
'size': ['XS', 'S', 'M', 'L', 'XL'],
sort_mapping = df_mapping.reset_index().set_index('size')

after , Use sort_mapping Create a new column with the mapping values in size_num.

df['size_num'] = df['size'].map(sort_mapping['index'])

Last , Sort values by new column size .


This, of course, is our job . But it creates an alternate column , Efficiency may be reduced when dealing with large data sets .

We can use CategoricalDtype To solve this problem more effectively .

Use CategoricalDtype Cast data to an ordered category type

CategoricalDtype Is a type of categorical data with a category and order [1]. It's very useful for creating custom sorts [2]. Let's take an example to see how this works .

First , Let's import CategoricalDtype.

from pandas.api.types import CategoricalDtype

then , Create a custom category type cat_size_order

  • The first parameter is set to ['XS'、'S'、'M'、'L'、'XL'] As a unique value of size .

  • The second parameter ordered=True, Think of this variable as ordered .

cat_size_order = CategoricalDtype(
['XS', 'S', 'M', 'L', 'XL'],

then , call astype(cat_size_order) Cast size data to a custom category type . By running df['size'], We can see size Column has been converted to a category type , The order is [XS<S<M<L<XL].

>>> df['size'] = df['size'].astype(cat_size_order)
>>> df['size']
0 S
1 XL
2 M
3 XS
4 L
5 S
Name: size, dtype: category
Categories (5, object): [XS < S < M < L < XL]

Last , We can call the same method to sort the values .


It works better . Let's see what the principle is .

Use cat Of codes Attribute access

Now? size Column has been converted to category type , We can use .cat Accessor to view the classification properties . Behind the scenes , It USES codes Property to represent the size of an ordered variable .

Let's create a new column code , So we can compare size and code values side by side .

df['codes'] = df['size']

We can see XS、S、M、L and XL The codes for are 0、1、2、3、4 and Is the actual value of the category . By running, We can see that it's actually int8.

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
 # Column Non-Null Count Dtype 
--- ------ -------------- ----- 
0 cloth_id 6 non-null int64 
1 size 6 non-null category
2 codes 6 non-null int8 
dtypes: category(1), int64(1), int8(1)
memory usage: 388.0 bytes

Sort by multiple variables

Next , Let's make things a little more complicated . here , We will sort the data frames by multiple variables .

df = pd.DataFrame({
'order_id': [1001, 1002, 1003, 1004, 1005, 1006, 1007],
'customer_id': [10, 12, 12, 12, 10, 10, 10],
'month': ['Feb', 'Jan', 'Jan', 'Feb', 'Feb', 'Jan', 'Feb'],
'day_of_week': ['Mon', 'Wed', 'Sun', 'Tue', 'Sat', 'Mon', 'Thu'],

Similarly , Let's create two custom category types cat_day_of_week and cat_month, And pass them on to astype().

cat_day_of_week = CategoricalDtype(
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
cat_month = CategoricalDtype(
['Jan', 'Feb', 'Mar', 'Apr'],
df['day_of_week'] = df['day_of_week'].astype(cat_day_of_week)
df['month'] = df['month'].astype(cat_month)

To sort by multiple variables , We just need to pass a list instead of sort_values(). for example , Press month and day_of_week Sort .

df.sort_values(['month', 'day_of_week'])

Press ustomer_id,month and day_of_week Sort .

df.sort_values(['customer_id', 'month', 'day_of_week'])

That's it , Thanks for reading .

In my, please Github Export the notebook to get the source code :


Link to the original text :

Welcome to join us AI Blog station :

sklearn Machine learning Chinese official documents :

Welcome to pay attention to pan Chuang blog resource summary station :

本文为[Artificial intelligence meets pioneer]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database