本文首发于微信公众号“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”(不含引号)

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

  1. python. pandas(series,dataframe,index) method test

    python. pandas(series,dataframe,index,reindex,csv file read and write) method test import pandas as ...

  2. python pandas.Series&&DataFrame&& set_index&reset_index

    参考CookBook :http://pandas.pydata.org/pandas-docs/stable/cookbook.html Pandas set_index&reset_ind ...

  3. python pandas ---Series,DataFrame 创建方法,操作运算操作(赋值,sort,get,del,pop,insert,+,-,*,/)

    pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包 pandas 也是围绕着 Series 和 DataFrame 两个核心数据结构展开的, 导入如下: from panda ...

  4. 吴裕雄--天生自然python学习笔记:pandas模块DataFrame 数据的修改及排序

    import pandas as pd datas = [[65,92,78,83,70], [90,72,76,93,56], [81,85,91,89,77], [79,53,47,94,80]] ...

  5. python基础:如何使用python pandas将DataFrame转换为dict

    之前在知乎上看到有网友提问,如何将DataFrame转换为dict,专门研究了一下,pandas在0.21.0版本中是提供了这个方法的.下面一起学习一下,通过调用help方法,该方法只需传入一个参数, ...

  6. python学习笔记—DataFrame和Series的排序

    更多大数据分析.建模等内容请关注公众号<bigdatamodeling> ################################### 排序 ################## ...

  7. python 数据处理学习pandas之DataFrame

    请原谅没有一次写完,本文是自己学习过程中的记录,完善pandas的学习知识,对于现有网上资料的缺少和利用python进行数据分析这本书部分知识的过时,只好以记录的形势来写这篇文章.最如果后续工作定下来 ...

  8. oracle数据据 Python+Pandas 获取Oracle数据库并加入DataFrame

    import pandas as pd import sys import imp imp.reload(sys) from sqlalchemy import create_engine impor ...

  9. 【跟着stackoverflow学Pandas】 - Adding new column to existing DataFrame in Python pandas - Pandas 添加列

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

随机推荐

  1. Atom打造 c/c++编译环境(忙了一个上午)

    众所周知 Atom是一款非常酷炫的编辑器.因为它就像上古卷轴一样,玩家可以开发各种dlc补丁,实现自己想要的效果.所以Atom 可以被你改造成自己想要的东西,可以用来写算法竞赛题目,可以开发网页,可以 ...

  2. 好看的复选框(Checkbox)效果

    在线演示      源码下载

  3. bzoj2560 串珠子

    Description 铭铭有n个十分漂亮的珠子和若干根颜色不同的绳子.现在铭铭想用绳子把所有的珠子连接成一个整体. 现在已知所有珠子互不相同,用整数1到n编号.对于第i个珠子和第j个珠子,可以选择不 ...

  4. hdu4027线段树

    https://vjudge.net/contest/66989#problem/H 此题真是坑到爆!!说好的四舍五入害我改了一个多小时,不用四舍五入!!有好几个坑点,注意要交换l,r的位置,还有输出 ...

  5. jQuery的hover方法搭配css的hover选择器,实现选中元素突出显示

    问题简述: 今天做帮一个师姐做网页遇到一个这样的要求: 鼠标不移动进表格,表格透明度不变. 鼠标移动进表格,hover到的单元格透明度不变,没hover到的单元格透明度改变. 先贴我已经实现好的效果, ...

  6. JDBC连接错误(Illegal mix of collations。。。)

    连接java和mysql时出现了这样的报错: java.sql.SQLException: Illegal mix of collations (latin1_swedish_ci,IMPLICIT) ...

  7. centOS的命令行与图形页面之间的转换

    .命令行 -> 图形界面 注意:在安装CentOS7的时候要添加GUI图形界面,否则没有效果. # startx

  8. WebSocket实战

    前言 互联网发展到现在,早已超越了原始的初衷,人类从来没有像现在这样依赖过他:也正是这种依赖,促进了互联网技术的飞速发展.而终端设备的创新与发展,更加速了互联网的进化: HTTP/1.1规范发布于19 ...

  9. 从编译器角度理解C++中的引用和指针

    欲分析指针和引用,则要分析变量名和地址之间的关系(不管你理解还是不理解,无论你是从老师那里听到的,还是网上看到的,应该都知道两句话:1. 指针就是地址,2.引用就是给变量起个别名) 所以我们就要来分析 ...

  10. centos永久修改主机名

    永久修改主机名 以上的修改只是临时修改,重启后就恢复原样了. 步骤1: 修改/etc/sysconfig/network中的hostname vi /etc/sysconfig/network HOS ...