我有一个 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"]
具体订单以列表myorder
通知为准
最佳答案
使用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
关于Python Pandas - 使用特定顺序重新索引数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48804909/