pandas中set_index方法是专门用来将某一列设置为index的方法。它具有简单,方便,快捷的特点。
主要参数:
keys:需要设置为index的列名
drop:True or False。在将原来的列设置为index,是否需要删除原来的列。默认为True,即删除(Delete columns to be used as the new index.)
append:True or False。新的index设置之后,是否要删除原来的index。默认为True。(Whether to append columns to existing index.)
inplace:True or False。是否要用新的DataFrame取代原来的DataFrame。默认False,即不取代。( Modify the DataFrame in place (do not create a new object))
举例如下:
>>> import pandas as pd
>>> import numpy as np
>>> dff=pd.read_excel(r'D:/myExcel/1.xlsx')
>>> dff
id name score grade
0 a bog 45.0 A
1 c jiken 67.0 B
2 i bob 23.0 A
3 b jiken 34.0 B
4 g lucy NaN A
5 e tidy 75.0 B
(1)设置id列为新的index
>>> dff.set_index('id')
name score grade
id
a bog 45.0 A
c jiken 67.0 B
i bob 23.0 A
b jiken 34.0 B
g lucy NaN A
e tidy 75.0 B
(2)将id列设置为index之后,并保留原来的列
>>> dff.set_index('id', drop=False)
id name score grade
id
a a bog 45.0 A
c c jiken 67.0 B
i i bob 23.0 A
b b jiken 34.0 B
g g lucy NaN A
e e tidy 75.0 B
(3)保留原来的index列
>>> dff.set_index('id', append=True)
name score grade
id
0 a bog 45.0 A
1 c jiken 67.0 B
2 i bob 23.0 A
3 b jiken 34.0 B
4 g lucy NaN A
5 e tidy 75.0 B
(4)使用inplace参数取代原来的对象
>>> dff.set_index('id', inplace=True)
>>> dff
name score grade
id
a bog 45.0 A
c jiken 67.0 B
i bob 23.0 A
b jiken 34.0 B
g lucy NaN A
e tidy 75.0 B
(5)通过新建Series并将其设置为index
>>> dff.set_index(pd.Series(range(6)))
name score grade
0 bog 45.0 A
1 jiken 67.0 B
2 bob 23.0 A
3 jiken 34.0 B
4 lucy NaN A
5 tidy 75.0 B
哈哈,以上就是python小工具关于set_index的方法的使用,有兴趣的话欢迎关注公众号:python小工具。一起学习python和pandas