Python全系列 教程
3567个小节阅读:5930.4k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在Pandas中,sort_index
方法用于对DataFrame或Series按照索引进行排序。它可以按照索引的升序或降序对数据进行重新排序。
xxxxxxxxxx
df.sort_index(level,ascending,inplace,na_position)
level :(多重索引时)指定用于排序的级别顺序号/名称
ascending = True :是否为升序排列,多列时以表形式提供
inplace = False :
na_position = 'last' :缺失值的排列顺序
xxxxxxxxxx
import pandas as pd
df = pd.DataFrame({'A': [3, 1, 4, 2]}, index=['b', 'd', 'c', 'a'])
# 按照索引的升序排序
sorted_df = df.sort_index()
print(sorted_df)
# 输出:
# A
# a 2
# b 3
# c 4
# d 1
# 按照索引的降序排序
sorted_df = df.sort_index(ascending=False)
print(sorted_df)
# 输出:
# A
# d 1
# c 4
# b 3
# a 2
xxxxxxxxxx
import pandas as pd
s = pd.Series([3, 1, 4, 2], index=['b', 'd', 'c', 'a'])
# 按照索引的升序排序
sorted_s = s.sort_index()
print(sorted_s)
# 输出:
# a 2
# b 3
# c 4
# d 1
# dtype: int64
# 按照索引的降序排序
sorted_s = s.sort_index(ascending=False)
print(sorted_s)
# 输出:
# d 1
# c 4
# b 3
# a 2
# dtype: int64