赞
踩
import pandas as pd
#数据集
df = pd.DataFrame({'word':['a','b','c'], 'num':[2,1,3]})
#自定义排序顺序,此顺序对应为升序ascending=True
list_sorted = ['b', 'a', 'c']
#对相关列进行自定义排序
df['word'] = df['word'].astype('category').cat.set_categories(list_sorted)
#结果
df_sortes = df.sort_values(by=['word'], ascending=True)
根据指定的list_sorted所包含元素比DataFrame中需要排序的列的元素的多或少,进行自定义排序时可以分为三种情况:
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。