首页 > 解决方案 > Python Dataframe 中值的自定义重新排序

问题描述

import pandas as pd
import numpy as np 

table = pd.DataFrame()

table["SORT_WW"]= ["03", "50", "01", "52", "03", "48", "02", "47"]
table ["Name"] = ["a", "b", "c", "d", "e", "f", "g", "h"]

我现在的表是这样的:

当前订单

我需要的订单:

SORT_WW_reorder = pd.Categorical(['45', '44', '46', '47', '48', '49', '50','51', '52', '53', '01', '02', '03', '04', '05', '06', '07'], ordered = True)

我在阅读 Stackoverflow 答案后尝试了什么:

SORT_WW_reorder = pd.Categorical(['45', '44', '46', '47', '48', '49', '50','51', '52', '53', '01', '02', '03', '04', '05', '06', '07'], ordered = True)

table.reindex(SORT_WW_reorder)

一旦我单击 Spyder 上的数据框“表”,它就不会做任何事情(我共享的图像相同 = 顺序相同,没有更新)。我错过了什么?

标签: pythonnumpydataframe

解决方案


据我了解,您希望根据 SORT_WW 中的值如何映射到有序分类数组中的位置来重新排序行。

这是一个通过将分类数组转换为 来获取排序索引的选项Index

df.iloc[pd.Index(SORT_WW_reorder).get_indexer(df.SORT_WW).argsort()]                                                                                 

  SORT_WW Name
7      47    h
5      48    f
1      50    b
3      52    d
2      01    c
6      02    g
0      03    a
4      03    e

推荐阅读