python的DataFrame排序问题

来源:互联网 发布:万方医药数据信息平台 编辑:程序博客网 时间:2024/06/07 00:01

一、定义数据框DataFrame

import  pandasframe = pandas.DataFrame({"a":[9,2,5,1],"b":[4,7,-3,2],"c":[6,5,8,3]})frameOut[53]:    a  b  c0  9  4  61  2  7  52  5 -3  83  1  2  3


二、按列对DataFrame排序

1.  按1列排序

(1)升序

frame.sort(columns = ['a'],axis = 0,ascending = True)Out[62]:    a  b  c3  1  2  31  2  7  52  5 -3  80  9  4  6frame.sort_index(axis = 0,ascending = True,by = 'a')Out[63]:    a  b  c3  1  2  31  2  7  52  5 -3  80  9  4  6frame.sort_values(by = 'a',axis = 0,ascending = True)Out[65]:    a  b  c3  1  2  31  2  7  52  5 -3  80  9  4  6

(2)降序

frame.sort(columns = ['a'],axis = 0,ascending = False)Out[67]:    a  b  c0  9  4  62  5 -3  81  2  7  53  1  2  3frame.sort_index(axis = 0,ascending = False,by = 'a')Out[68]:    a  b  c0  9  4  62  5 -3  81  2  7  53  1  2  3frame.sort_values(by = 'a',axis = 0,ascending = False)
Out[69]:    a  b  c0  9  4  62  5 -3  81  2  7  53  1  2  3

2.  按多列排序
frame = pandas.DataFrame({"a":[9,2,5,1,0,7],"b":[4,7,-3,2,2,2],"c":[6,5,8,3,4,4]})frameOut[73]:    a  b  c0  9  4  61  2  7  52  5 -3  83  1  2  34  0  2  45  7  2  4

(1)升序

frame.sort(columns = ['b','c','a'],axis = 0,ascending = True)Out[74]:    a  b  c2  5 -3  83  1  2  34  0  2  45  7  2  40  9  4  61  2  7  5frame.sort_index(axis = 0,ascending = True,by = ['b','c','a'])Out[75]:    a  b  c2  5 -3  83  1  2  34  0  2  45  7  2  40  9  4  61  2  7  5frame.sort_values(by = ['b','c','a'],axis = 0,ascending = True)Out[76]:    a  b  c2  5 -3  83  1  2  34  0  2  45  7  2  40  9  4  61  2  7  5

(2)降序

rame.sort(columns = ['b','c','a'],axis = 0,ascending = False)Out[77]:    a  b  c1  2  7  50  9  4  65  7  2  44  0  2  43  1  2  32  5 -3  8frame.sort_index(axis = 0,ascending = False,by = ['b','c','a'])Out[78]:    a  b  c1  2  7  50  9  4  65  7  2  44  0  2  43  1  2  32  5 -3  8frame.sort_values(by = ['b','c','a'],axis = 0,ascending = False)Out[79]:    a  b  c1  2  7  50  9  4  65  7  2  44  0  2  43  1  2  32  5 -3  8



三、按行对DataFrame排序

data = {"b":[4,7,-3,2,2,2],"a":[9,2,5,1,0,7],"c":[6,5,8,3,4,4]}frame = pandas.DataFrame(data,columns = ['b','a','c'])frameOut[90]:    b  a  c0  4  9  61  7  2  52 -3  5  83  2  1  34  2  0  45  2  7  4

1. 按行升序

frame.sort_index(axis = 1,ascending = True)Out[91]:    a  b  c0  9  4  61  2  7  52  5 -3  83  1  2  34  0  2  45  7  2  4

2. 按行降序

frame.sort_index(axis = 1,ascending = False)Out[97]:    c  b  a0  6  4  91  5  7  22  8 -3  53  3  2  14  4  2  05  4  2  7




相关链接:

http://blog.csdn.net/qq_22238533/article/details/72395564


http://bluewhale.cc/2016-08-06/use-pandas-filter-and-sort.html


http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html#pandas.DataFrame.sort_index


http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html#pandas.DataFrame.sort_values