文档详情

Python数据分析基础与应用电子活页4-6使用set_index( )函数设置索引.docx

发布:2025-05-29约1.59千字共2页下载文档
文本预览下载声明

Python数据分析基础与应用

模块

PAGE2

PAGE21

电子活页4-6使用set_index()函数设置索引

【技能训练4-10】使用set_index()函数设置索引

【训练要求】

在JupyterNotebook开发环境中创建j4-10.ipynb,然后编写代码使用set_index()函数设置索引。

【实施过程】

(1)创建DataFrame对象

代码如下:

importpandasaspd

data1={id:[1,2,3,4],

name:[安静,向北,路远,温暖],

sex:[女,女,男,男],

age:[21,22,20,19],

height:[171,166,180,189]}

label1=[stu1,stu2,stu3,stu4]

df1=pd.DataFrame(data1,index=label1)

print(df1)

输出结果:

idnamesexageheight

stu11安静女21171

stu22向北女22166

stu33路远男20180

stu44温暖男19189

(2)设置单索引

代码如下:

print(df1.set_index(id))

输出结果:

namesexageheight

id

1安静女21171

2向北女22166

3路远男20180

4温暖男19189

(3)设置复合索引

代码如下:

print(df1.set_index([sex,name]))

输出结果:

idageheight

sexname

女安静121171

向北222166

男路远320180

温暖419189

(4)保留用作新索引的列

代码如下:

print(df1.set_index(id,drop=False))

输出结果:

idnamesexageheight

id

11安静女21171

22向北女22166

33路远男20180

44温暖男19189

(5)原来的索引和新索引一起被保留下来

代码如下:

print(df1.set_index(id,append=True))

输出结果:

namesexageheight

id

stu11安静女21171

stu22向北女22166

stu33路远男20180

stu44温暖男19189

显示全部
相似文档