文档详情

Python数据分析基础与应用电子活页4-8使用reindex()函数重置索引排列顺序.docx

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

Python数据分析基础与应用

模块

PAGE2

PAGE3

电子活页4-8使用reindex()函数重置索引排列顺序

【技能训练4-12】使用reindex()函数重置索引排列顺序

【训练要求】

在JupyterNotebook开发环境中创建j4-12.ipynb,然后编写代码使用reindex()函数重置索引排列顺序。

【实施过程】

(1)对Series使用reindex()函数重置索引排列顺序

代码如下:

importpandasaspd

s1=pd.Series([21,22,20,19],index=[d,b,a,c])

print(s1.reindex([a,b,c,d,e]))

输出结果:

a20.0

b22.0

c19.0

d21.0

eNaN

dtype:float64

代码如下:

#使用fill_value()参数指定不存在元素的默认值为0

print(s1.reindex([a,b,c,d,e],fill_value=0))

输出结果:

a20

b22

c19

d21

e0

dtype:int64

代码如下:

s2=pd.Series([blue,red,yellow],index=[0,2,4])

#使用ffill函数前向填充

s2.reindex(range(6),method=ffill)

输出结果:

0blue

1blue

2red

3red

4yellow

5yellow

dtype:object

(2)对DataFrame使用reindex()函数重置行索引或列索引的排列顺序

代码如下:

importpandasaspd

data1={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(data1)

#重置行、列索引的排列顺序

df2=df1.reindex(index=[4,0,2],columns=[date,AQI,highT,lowT])

print(df2)

输出结果:

dateAQIhighTlowT

42022/1/510475

02022/1/1167121

22022/1/3123128

代码如下:

#为DataFrame添加一个新的行

df3=df1.reindex(index=[4,0,2,5])

print(df3)

输出结果:

datehighTlowTAQI

42022/1/57.05.0104.0

02022/1/112.01.0167.0

22022/1/312.08.0123.0

5NaNNaNNaNNaN

代码如下:

#使用ffill函数前向填充

df3=df1.reindex(index=[4,0,2,5],method=ffill)

print(df3)

输出结果:

datehighTlowTAQI

42022/1/575104

02022/1/1121167

22022/1/3128123

52022/1/575104

代码如下:

#为DataFrame添加一个新的列

df4=df1.reindex(columns=[date,AQI,highT,lowT,grade])

print(df4)

输出结果:

dateAQIhighTlowTgrade

02022/1/1167121NaN

12022/1/2145154NaN

22022/1/3123128NaN

32022/1/4212

显示全部
相似文档