Pandas索引排序 df.sort_index()的实现
作者:山茶花开时。 时间:2023-02-13 23:49:48
df.sort_index()实现按索引排序,默认以从小到大的升序方式排列,如希望按降序排列,传入ascending = False
import pandas as pd
df = pd.DataFrame([['liver','E',89,21,24,64],
['Arry','C',36,37,37,57],
['Ack','A',57,60,18,84],
['Eorge','C',93,96,71,78],
['Oah','D',65,49,61,86]
],
columns = ['name','team','Q1','Q2','Q3','Q4'])
# 索引降序
res1 = df.sort_index(ascending=False)
# 按列索引名排序:
# 在索引方向上排序
res2 = df.sort_index(axis=1, ascending=False)
结果展示
df
res1
res2
扩展
# 更多方法如下:
s.sort_index() # 升序排列
df.sort_index() # df也是按索引进行排序
df.team.sort_index()
s.sort_index(ascending=False) # 降序排列
s.sort_index(inplace=True) # 排序后生效,改变原数据
# 索引重新0-(n-1)排,可以得到它的排序号
s.sort_index(ignore_index=True)
s.sort_index(na_position='first') # 空值在前,另'last'表示空值在后
s.sort_index(level=1) # 如果多层,排一级
s.sort_index(level=1, sort_remaining=False) # 这层不排
# 行索引排序,表头排序
df.sort_index(axis=1) # 会把列按列名顺序排序
df.reindex()指定自己定义顺序的索引,实现行和列的顺序重新定义
import pandas as pd
df = pd.DataFrame({
'A':[1,2,3],
'B':[4,5,6]
},index=['a','b','c'])
# 按要求重新指定索引顺序
res1 = df.reindex(['c','b','a'])
# 指定列顺序
res2 = df.reindex(['B','A'], axis=1)
结果展示
df
res1
res2
来源:https://blog.csdn.net/Hudas/article/details/122923267
标签:Pandas,索引排序,df.sort,index()
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python在命令行下使用google翻译(带语音)
2023-06-02 13:47:17
IE6与IE7的unshift 方法
2010-01-19 13:59:00
如何让新安装的MySQL数据库变得更安全
2009-01-04 13:19:00
使用ajax开发的五大误区
2008-09-03 12:46:00
python+opencv实现高斯平滑滤波
2023-04-02 15:56:55
![](https://img.aspxhome.com/file/2023/1/82531_0s.jpg)
解决python ogr shp字段写入中文乱码的问题
2023-07-05 00:40:17
python中OrderedDict的使用方法详解
2023-08-26 14:00:40
脚本安全的本质_PHP+MYSQL第1/3页
2023-11-23 23:54:45
SQL SERVER 2005中的同步复制技术
2009-01-05 13:44:00
Python生成器(Generator)详解
2022-10-05 01:14:43
python ConfigParser库的使用及遇到的坑
2021-08-13 05:45:23
![](https://img.aspxhome.com/file/2023/7/66837_0s.jpg)
浅谈 Mousewheel 事件
2010-08-16 12:37:00
python实现打印类的所有属性和方法
2021-07-28 14:51:56
![](https://img.aspxhome.com/file/2023/2/67902_0s.png)
Python实现字符串模糊匹配方式
2023-11-10 09:30:35
![](https://img.aspxhome.com/file/2023/4/64644_0s.png)
取巧的边框等高
2009-12-16 12:11:00
![](https://img.aspxhome.com/file/UploadPic/200912/16/css_border-13s.png)
解决django接口无法通过ip进行访问的问题
2023-09-15 14:07:27
![](https://img.aspxhome.com/file/2023/6/62266_0s.jpg)
python神经网络学习利用PyTorch进行回归运算
2023-02-24 13:30:47
打造设计你自己的字体
2007-12-12 13:16:00
![](https://img.aspxhome.com/file/UploadPic/200712/12/20071212132556860s.jpg)
在Pycharm中使用GitHub的方法步骤
2021-04-27 04:46:48
![](https://img.aspxhome.com/file/2023/4/83654_0s.png)
详解pytorch 0.4.0迁移指南
2023-04-10 08:02:14
![](https://img.aspxhome.com/file/2023/0/84920_0s.jpg)