2023年7月26日发(作者:)
Python:pandas的DataFrame如何按指定list排序前⾔写这篇⽂章的起由是有⼀天微信上⼀位朋友问到⼀个问题,问题⼤体意思概述如下:现在有⼀个pandas的Series和⼀个python的list,想让Series按指定的list进⾏排序,如何实现?这个问题的需求⽤流程图描述如下:我思考了⼀下,这个问题解决的核⼼是引⼊pandas的数据类型“category”,从⽽进⾏排序。在具体的分析过程中,先将pandas的Series转换成为DataFrame,然后设置数据类型,再进⾏排序。思路⽤流程图表⽰如下:分析过程引⼊pandas库import pandas as pd构造Series数据s = ({'a':1,'b':2,'c':3})sa 1b 2c 3dtype: ndex(['a', 'b', 'c'], dtype='object')指定的list,后续按指定list的元素顺序进⾏排序list_custom = ['b', 'a', 'c']list_custom['b', 'a', 'c']将Series转换成DataFramedf = ame(s)df = _index()s = ['words', 'number']设置成“category”数据类型# 设置成“category”数据类型df['words'] = df['words'].astype('category')# inplace = True,使 recorder_categories⽣效df['words'].r_categories(list_custom, inplace=True)# inplace = True,使 df⽣效_values('words', inplace=True)指定list元素多的情况:若指定的list所包含元素⽐Dataframe中需要排序的列的元素多,怎么办?reorder_catgories()⽅法不能继续使⽤,因为该⽅法使⽤时要求新的categories和dataframe中的categories的元素个数和内容必须⼀致,只是顺序不同。这种情况下,可以使⽤ set_categories()⽅法来实现。新的list可以⽐dataframe中元素多。list_custom_new = ['d', 'c', 'b','a','e']dict_new = {'e':1, 'b':2, 'c':3}df_new = ame(list(dict_()), columns=['words', 'value'])print(list_custom_new)df__values('words', inplace=True)df_new['d', 'c', 'b', 'a', 'e']_new['words'] = df_new['words'].astype('category')# inplace = True,使 set_categories⽣效df_new['words']._categories(list_custom_new, inplace=True)df__values('words', ascending=True)指定list元素少的情况:若指定的list所包含元素⽐Dataframe中需要排序的列的元素少,怎么办?这种情况下,set_categories()⽅法还是可以使⽤的,只是没有的元素会以NaN表⽰注意下⾯的list中没有元素“b”list_custom_new = ['d', 'c','a','e']dict_new = {'e':1, 'b':2, 'c':3}df_new = ame(list(dict_()), columns=['words', 'value'])print(list_custom_new)df__values('words', inplace=True)df_new['d', 'c', 'a', 'e']_new['words'] = df_new['words'].astype('category')# inplace = True,使 set_categories⽣效df_new['words']._categories(list_custom_new, inplace=True)df__values('words', ascending=True)总结根据指定的list所包含元素⽐Dataframe中需要排序的列的元素的多或少,可以分为三种情况:相等的情况下,可以使⽤ reorder_categories和 set_categories⽅法;list的元素⽐较多的情况下, 可以使⽤set_categories⽅法;list的元素⽐较少的情况下, 也可以使⽤set_categories⽅法,但list中没有的元素会在DataFrame中以NaN表⽰。源代码需要的童鞋可在微信公众号“Python数据之道”(ID:PyDataRoad)后台回复关键字获取视频,关键字如下:“2017-025”(不含引号)
发布者:admin,转转请注明出处:http://www.yc00.com/web/1690305599a329590.html
评论列表(0条)