Compared with excel, how to implement "custom text" sorting in Python!

Sorting "for numerical data" may be everyone's favorite and most familiar operation, but how to sort "for text data"? This question, you can meditate in your heart, how to operate.

Sometimes, if a small piece of data can be used directly in Excel to complete the requirement, how to use it to operate it? If the amount of data is large and you want to use Python to achieve this goal, what should you do?

Based on this, classmate Huang will take everyone today to implement these two requirements in Excel and Python respectively.

Data introduction

There are the following three columns of data. For the "Education" field, sort by "College", "Undergraduate", and "Graduate". For different academic qualifications, they are arranged in descending order of "basic salary".
Insert picture description here

Excel implementation

① Select all data

Insert picture description here

② Click Start --> Sort and Filter --> Custom Sort

Insert picture description here

③ When the following interface appears, complete the operation in the figure

Insert picture description here

④ When the following interface appears, complete the operation in the figure

Insert picture description here

⑤ When the following interface appears, complete the operation in the figure

Insert picture description here

⑥ The effect is as follows

Insert picture description here

Python implementation

import pandas as pd

# 自定义一个序列
x = [ '研究生', '本科', '大专']

# 读取数据
df = pd.read_excel("测试.xlsx")

# 将“学历”列设置为category数据类型
df["学历"] = df["学历"].astype("category")

# reorder_categories表示重新排序在x序列中指定的类别
# inplace=True表示对现有类别重新排序
df["学历"].cat.reorder_categories(x, inplace=True)

# 然后采用多列排序的方式,对“学历”列按照指定x顺序排列,对“基本工资”列进行降序排列
df.sort_values(by=["学历","基本工资"], inplace=True,ascending=[True,False])
df

final effect:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41261833/article/details/109165957