pandas 对series和dataframe进行排序的实例

yipeiwu_com6年前Python基础

本问主要写根据索引或者值对series和dataframe进行排序的实例讲解

代码:

#coding=utf-8
import pandas as pd
import numpy as np
#以下实现排序功能。
series=pd.Series([3,4,1,6],index=['b','a','d','c'])
frame=pd.DataFrame([[2,4,1,5],[3,1,4,5],[5,1,4,2]],columns=['b','a','d','c'],index=['one','two','three'])
print frame
print series
print 'series通过索引进行排序:'
print series.sort_index()
print 'series通过值进行排序:'
print series.sort_values()
print 'dataframe根据行索引进行降序排序(排序时默认升序,调节ascending参数):'
print frame.sort_index(ascending=False)
print 'dataframe根据列索引进行排序:'
print frame.sort_index(axis=1)
print 'dataframe根据值进行排序:'
print frame.sort_values(by='a')
print '通过多个索引进行排序:'
print frame.sort_values(by=['a','c'])

实验结果:

  b a d c
one 2 4 1 5
two 3 1 4 5
three 5 1 4 2

b 3
a 4
d 1
c 6
dtype: int64

series通过索引进行排序:

a 4
b 3
c 6
d 1
dtype: int64

series通过值进行排序:

d 1
b 3
a 4
c 6
dtype: int64

dataframe根据行索引进行降序排序(排序时默认升序,调节ascending参数):

  b a d c
two 3 1 4 5
three 5 1 4 2
one 2 4 1 5

dataframe根据列索引进行排序:

  a b c d
one 4 2 5 1
two 1 3 5 4
three 1 5 2 4

dataframe根据值进行排序:

  b a d c
two 3 1 4 5
three 5 1 4 2
one 2 4 1 5

通过两个索引进行排序:

  b a d c
three 5 1 4 2
two 3 1 4 5
one 2 4 1 5
[Finished in 1.0s]

以上这篇pandas 对series和dataframe进行排序的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python动态加载变量示例分享

众所周知,程序在启动后,各个程序文件都会被加载到内存中,这样如果程序文本再次变化,对当前程序的运行没有影响,这对程序是一种保护。 但是,对于像python这样解释执行的语言,我们有时候会...

python能做什么 python的含义

python能做什么?是什么意思? Python是一种跨平台的计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能...

windows下pycharm安装、创建文件、配置默认模板

windows下pycharm安装、创建文件、配置默认模板

本文为大家分享了windows下pycharm安装、创建文件、配置默认模板的具体步骤,供大家参考,具体内容如下 步骤: 下包 —->安装——>创建文件—->定制模板...

python计算牛顿迭代多项式实例分析

本文实例讲述了python计算牛顿迭代多项式的方法。分享给大家供大家参考。具体实现方法如下: ''' p = evalPoly(a,xData,x). Evaluates New...

python 根据时间来生成唯一的字符串方法

我们很多时候,特别是在生成任务的时候,都需要一个唯一标识字符串来标识这个任务,比较常用的有生成uuid或者通过时间来生成。uuid的话可以直接通过uuid模块来生成。如果是时间的话,可以...