简体   繁体   English

Python Pandas - 使用特定订单重新索引数据框

[英]Python Pandas - Re-index a dataframe using a specific order

I have a pandas data frame I want to reorder the index using a specific order. 我有一个pandas数据框我想使用特定的顺序重新排序索引。

from random import randint
import pandas as pd
days = ["Tuesday", "Thursday", "Monday", "Wednesday"]
df = pd.DataFrame({"Value": [randint(0, 9) for i in range(len(days)*2)]}, 
                  index=[day for day in days for i in range(2)])
myorder = ["Monday", "Tuesday", "Wednesday", "Thursday"]

The specific order is as notified by the list myorder 具体顺序由列表myorder通知

Use CategoricalIndex + sort_index : 使用CategoricalIndex + sort_index

df.index = pd.CategoricalIndex(df.index, categories=myorder, ordered=True)
df = df.sort_index()
print (df)
           Value
Monday         3
Monday         3
Tuesday        4
Tuesday        3
Wednesday      3
Wednesday      4
Thursday       5
Thursday       2

This is one method, if you wish to avoid categoricals: 如果您希望避免使用分类,这是一种方法:

orderdic = dict(zip(myorder, range(len(myorder))))

df = df.assign(order=df.index.to_series().map(orderdic))\
       .sort_values('order').drop('order', 1)

#            Value
# Monday         6
# Monday         6
# Tuesday        9
# Tuesday        1
# Wednesday      1
# Wednesday      3
# Thursday       0
# Thursday       7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM