python中DataFrame、Series数据类型 sort 排序

 
 
 
 
 
 

1、DataFrame类型排序

import pandas as pd
import numpy as np
### 随机生成 DataFrame类型数据
frame = pd.DataFrame(np.random.randn(5,4),index=list('34125'),columns=list('BACD'))
frame
     B A C D
3 0.923768 -1.046159 0.360164 -0.169505
4 -1.347206 2.449790 -0.111024 -0.027890
1 0.426441 -1.068556 0.831686 1.141934
2 -0.889661 0.637654 1.612614 -0.917645
5 -0.487280 -0.228530 -1.454767 -1.843402
### 对frame行索引(index)排序 ,axis默认为0,默认升序,即ascending=True
### frame.sort_index(ascending=False)   对行索引降序排列
frame.sort_index()
  B A C D
1 0.426441 -1.068556 0.831686 1.141934
2 -0.889661 0.637654 1.612614 -0.917645
3 0.923768 -1.046159 0.360164 -0.169505
4 -1.347206 2.449790 -0.111024 -0.027890
5 -0.487280 -0.228530 -1.454767 -1.843402
### 对frame列索引(columns)排序 ,默认升序,即ascending=True
### 对frame列索引(columns)降序排列,即ascending=False
frame.sort_index(axis=1,ascending=False)  
  D C B A
3 -0.169505 0.360164 0.923768 -1.046159
4 -0.027890 -0.111024 -1.347206 2.449790
1 1.141934 0.831686 0.426441 -1.068556
2 -0.917645 1.612614 -0.889661 0.637654
5 -1.843402 -1.454767 -0.487280 -0.228530
### 对指定列的值对frame排序,默认升序
frame.sort_index(by = 'A')
  B A C D
1 0.426441 -1.068556 0.831686 1.141934
3 0.923768 -1.046159 0.360164 -0.169505
5 -0.487280 -0.228530 -1.454767 -1.843402
2 -0.889661 0.637654 1.612614 -0.917645
4 -1.347206 2.449790 -0.111024 -0.027890
### 行索引和列索引都按升序排列
s = frame.sort_index()
s.sort_index(axis=1)

  A B C D
1 -1.068556 0.426441 0.831686 1.141934
2 0.637654 -0.889661 1.612614 -0.917645
3 -1.046159 0.923768 0.360164 -0.169505
4 2.449790 -1.347206 -0.111024 -0.027890
5 -0.228530 -0.487280 -1.454767 -1.843402

2、Series类型排序

### 生成Series类型数据
s = pd.Series(['15','10','18','16'],index=list('acbd'))
s
a    15
c    10
b    18
d    16
dtype: object
### 按索引排列
s.sort_index()
a    15
b    18
c    10
d    16
dtype: object
### 按值排列,默认升序,ascending=True
s.sort_values()
c    10
a    15
d    16
b    18
dtype: object

猜你喜欢

转载自blog.csdn.net/qq_21840201/article/details/80720796
今日推荐