Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to sort according to the specified string sequence in python

Shulou Source: shulou.com Published: 2022-06-02 05:30:25 11月11日 Update

This article introduces you how to sort in python according to the specified string sequence, the content is very detailed, interested friends can refer to it, I hope it can help you.

Raw Data Preview

It is evident from the table below that all the regions are arranged in disorder. This friend just wants to arrange the regions in the order of "Shenzhen, Guangzhou, Huizhou and Dongguan".

Some people may think that such a simple problem can not be done directly with Excel. That's true, but what if there are multiple such forms? And it's repeated every day. Do you still think manual operation is more convenient?

3. solve problems

To be honest, this is the first time I have encountered this problem in Python. I only remember that I completed this requirement in Excel at that time. How to deal with it in Python? I really wasn't thinking. So this knowledge point is new to me, and I think it's probably new to most of you.

import pandas as pd

#Customize a sequence

x = ['Shenzhen',' Guangzhou','Huizhou',' Dongguan']

#Read the data

df = pd.read_excel("workbook.xlsx")

#Set Region column to category data type

df["Region"] = df["Region"]. atype ("category")

# reorder_categories means to reorder the categories specified in the x sequence

# inplace=True to reorder existing categories

df["Region"].cat.reorder_categories(x, inplace=True)

df.sort_values("Region", inplace=True)

df

The results were as follows:

How to sort according to the specified string sequence in python is shared here. I hope the above content can be of some help to everyone and can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Tags: Region sequence sort knowledge data knowledge points questions characters strings content more categories Dongguan Guangzhou Huizhou Shenzhen help good original obvious Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Docker MariaDB vpn NVidia