Python: Pandas的DataFrame如何按指定list排序

本文首发于微信公众号“Python数据之道”(ID:PyDataRoad)

前言

写这篇文章的起由是有一天微信上一位朋友问到一个问题,问题大体意思概述如下:

现在有一个pandas的Series和一个python的list,想让Series按指定的list进行排序,如何实现?

这个问题的需求用流程图描述如下:

我思考了一下,这个问题解决的核心是引入pandas的数据类型“category”,从而进行排序。

在具体的分析过程中,先将pandas的Series转换成为DataFrame,然后设置数据类型,再进行排序。思路用流程图表示如下:

分析过程

  • 引入pandas库
import pandas as pd
  • 构造Series数据
s = pd.Series({‘a‘:1,‘b‘:2,‘c‘:3})
s
a    1
b    2
c    3
dtype: int64
s.index
Index([‘a‘, ‘b‘, ‘c‘], dtype=‘object‘)
  • 指定的list,后续按指定list的元素顺序进行排序
list_custom = [‘b‘, ‘a‘, ‘c‘]
list_custom
[‘b‘, ‘a‘, ‘c‘]
  • 将Series转换成DataFrame

    df = pd.DataFrame(s)
    df = df.reset_index()
    df.columns = [‘words‘, ‘number‘]
    df
    
  words number
0 a 1
1 b 2
2 c 3

设置成“category”数据类型

# 设置成“category”数据类型
df[‘words‘] = df[‘words‘].astype(‘category‘)
# inplace = True,使 recorder_categories生效
df[‘words‘].cat.reorder_categories(list_custom, inplace=True)

# inplace = True,使 df生效
df.sort_values(‘words‘, inplace=True)
df

  words number
1 b 2
0 a 1
2 c 3

指定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 = pd.DataFrame(list(dict_new.items()), columns=[‘words‘, ‘value‘])
print(list_custom_new)
df_new.sort_values(‘words‘, inplace=True)
df_new
[‘d‘, ‘c‘, ‘b‘, ‘a‘, ‘e‘]

  words value
0 b 2
1 c 3
2 e 1
df_new[‘words‘] = df_new[‘words‘].astype(‘category‘)

# inplace = True,使 set_categories生效
df_new[‘words‘].cat.set_categories(list_custom_new, inplace=True)

df_new.sort_values(‘words‘, ascending=True)

  words value
1 c 3
0 b 2
2 e 1

指定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 = pd.DataFrame(list(dict_new.items()), columns=[‘words‘, ‘value‘])
print(list_custom_new)
df_new.sort_values(‘words‘, inplace=True)
df_new
[‘d‘, ‘c‘, ‘a‘, ‘e‘]

  words value
0 b 2
1 c 3
2 e 1
df_new[‘words‘] = df_new[‘words‘].astype(‘category‘)

# inplace = True,使 set_categories生效
df_new[‘words‘].cat.set_categories(list_custom_new, inplace=True)

df_new.sort_values(‘words‘, ascending=True)

  words value
0 NaN 2
1 c 3
2 e 1

总结

根据指定的list所包含元素比Dataframe中需要排序的列的元素的多或少,可以分为三种情况:

  • 相等的情况下,可以使用 reorder_categories和 set_categories方法;
  • list的元素比较多的情况下, 可以使用set_categories方法;
  • list的元素比较少的情况下, 也可以使用set_categories方法,但list中没有的元素会在DataFrame中以NaN表示。

源代码

需要的童鞋可在微信公众号“Python数据之道”(ID:PyDataRoad)后台回复关键字获取视频,关键字如下:

2017-025”(不含引号)

?

时间: 2025-01-04 20:53:36

Python: Pandas的DataFrame如何按指定list排序的相关文章

python 数据处理学习pandas之DataFrame

请原谅没有一次写完,本文是自己学习过程中的记录,完善pandas的学习知识,对于现有网上资料的缺少和利用python进行数据分析这本书部分知识的过时,只好以记录的形势来写这篇文章.最如果后续工作定下来有时间一定完善pandas库的学习,请见谅!                     by LQJ 2015-10-25 前言: 首先推荐一个比较好的Python pandas DataFrame学习网址 网址: http://www.cnblogs.com/chaosimple/p/4153083

[python][pandas]DataFrame的基本操作

问题来源 在实验中经常需要将数据保存到易于查看的文件当中,由于大部分都是vector数据,所以选择pandas的dataframe来保存到csv文件是最简单的方法. 基本操作 下图是DataFrame的一些基本概念,可以看出与基本的csv结构是保持一致的. 1. 创建DataFrame 创建DataFrame通常有两种方法,从list中创建和从dict中创建: 从dict创建,key的名字会作为名,如下所示: >>> d = {'col1': [1, 2], 'col2': [3, 4]

Python pandas 0.19.1 Indexing and Selecting Data文档翻译

最近在写个性化推荐的论文,经常用到Python来处理数据,被pandas和numpy中的数据选取和索引问题绕的比较迷糊,索性把这篇官方文档翻译出来,方便自查和学习,翻译过程中难免很多不到位的地方,但大致能看懂,错误之处欢迎指正~ Python pandas 0.19.1 Indexing and Selecting Data 原文链接 http://pandas.pydata.org/pandas-docs/stable/indexing.html 数据索引和选取 pandas对象中的轴标签信息

Python array,list,dataframe索引切片操作 2016年07月19日——智浪文档

array,list,dataframe索引切片操作 2016年07月19日——智浪文档 list,一维,二维array,datafrme,loc.iloc.ix的简单探讨 Numpy数组的索引和切片介绍: 从最基础的list索引开始讲起,我们先上一段代码和结果: a = [0,1,2,3,4,5,6,7,8,9] a[:5:-1] #step < 0,所以start = 9 a[0:5:-1] #指定了start = 0 a[1::-1] #step < 0,所以stop = 0 输出: [

python pandas 中文件的读写——read_csv()读取文件

read_csv()读取文件1.python读取文件的几种方式read_csv 从文件,url,文件型对象中加载带分隔符的数据.默认分隔符为逗号read_table 从文件,url,文件型对象中加载带分隔符的数据.默认分隔符为制表符(“\t”)read_fwf 读取定宽列格式数据(也就是没有分隔符)read_cliboard 读取剪切板中的数据,可以看做read_table的剪切板.在将网页转换为表格时很有用2.读取文件的简单实现程序代码: df=pd.read_csv('D:/project/

Python中处理DataFrame,R绘图

IN Python from pandas import DataFrame,Series import pandas as pd import numpy as np data = pd.read_csv(r'C:\Users\lxy\Desktop\工作相关\工作报告KPI\pydata-book-master\ch06\ex5.csv') data.index.name='x' data.to_csv('D:\df.csv') IN R > library(ggplot2) > df &

将pandas的DataFrame数据写入MySQL数据库 + sqlalchemy

将pandas的DataFrame数据写入MySQL数据库 + sqlalchemy [python] view plain copy print? import pandas as pd from sqlalchemy import create_engine ##将数据写入mysql的数据库,但需要先通过sqlalchemy.create_engine建立连接,且字符编码设置为utf8,否则有些latin字符不能处理 yconnect = create_engine('mysql+mysql

pandas中DataFrame

python数据分析工具pandas中DataFrame和Series作为主要的数据结构. 本文主要是介绍如何对DataFrame数据进行操作并结合一个实例测试操作函数. 1)查看DataFrame数据及属性 df_obj = DataFrame() #创建DataFrame对象 df_obj.dtypes #查看各行的数据格式 df_obj['列名'].astype(int)#转换某列的数据类型 df_obj.head() #查看前几行的数据,默认前5行 df_obj.tail() #查看后几

Python Pandas库的学习(三)

今天我们来继续讲解Python中的Pandas库的基本用法 那么我们如何使用pandas对数据进行排序操作呢? food.sort_values("Sodium_(mg)",inplace= True) print(food["Sodium_(mg)"]) food.sort_values("Sodium_(mg)",inplace=True,ascending= False) print(food["Sodium_(mg)"