文档详情

Python数据分析基础与应用电子活页4-13实现Pandas的排序操作.docx

发布:2025-05-28约2.98千字共3页下载文档
文本预览下载声明

Python数据分析基础与应用

模块

PAGE2

PAGE3

电子活页4-13实现pandas的排序操作

【技能训练4-17】实现pandas的排序操作

【训练要求】

在JupyterNotebook开发环境中创建j4-17.ipynb,然后编写代码实现pandas的排序操作。

【实施过程】

1.使用sort_index()函数按索引标签进行排序

(1)创建指定行索引的DataFrame对象

代码如下:

importpandasaspd

data={date:pd.Series([2022/1/1,2022/1/2,2022/1/3,2022/1/4,2022/1/5]),

highT:pd.Series([12,15,12,12,7]),

lowT:pd.Series([1,4,8,6,5]),

AQI:pd.Series([167,145,123,212,104])}

df1=pd.DataFrame(data,index=[4,1,2,0,3])

print(df1)

输出结果:

datehighTlowTAQI

42022/1/575104

12022/1/2154145

22022/1/3128123

02022/1/1121167

32022/1/4126212

(2)按行索引顺序排列

代码如下:

df2=df1.sort_index()

print(df2)

输出结果:

datehighTlowTAQI

02022/1/1121167

12022/1/2154145

22022/1/3128123

32022/1/4126212

42022/1/575104

(3)通过ascending参数控制排序方式

代码如下:

df3=df1.sort_index(ascending=False)

print(df3)

输出结果:

datehighTlowTAQI

42022/1/575104

32022/1/4126212

22022/1/3128123

12022/1/2154145

02022/1/1121167

(4)按列索引顺序排列

代码如下:

df4=df1.sort_index(axis=1)

print(df4)

输出结果:

AQIdatehighTlowT

41042022/1/575

11452022/1/2154

21232022/1/3128

01672022/1/1121

32122022/1/4126

2.使用sort_values()函数按数值进行排序

(1)按1列的数值进行排序

代码如下:

df5=df1.sort_values(by=highT)#输出结果与df1.sort_values(by=highT,axis=0)的相同

print(df5)

输出结果:

datehighTlowTAQI

42022/1/575104

22022/1/3128123

02022/1/1121167

32022/1/4126212

12022/1/2154145

【注意】当按highT列排序时,相应的其他列(date、lowT、AQI)的元素值和行索引也会随highT列一起改变。

(2)按多列数值的升序进行排列

代码如下:

#先按highT列升序排列,highT列数值相同的按lowT列升序排列

df6=df1.sort_values(by=[highT,lowT])

print(df6)

输出结果:

datehighTlowTAQI

42022/1/575104

02022/1/1121167

显示全部
相似文档