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))
示例:
df = pd.DataFrame(np.random.randn(5,5),columns=["A","B","C","D","E"],index=["a","b","c","d","e"])
df['F']=[0,1,2,3,4]
df
1、设置F列作为index
df.set_index('F',inplace=True)
df
如果inpalce=False,原dataframe不改变。
2、drop=False:F列作为index后,原列在dataframe不删除
df.set_index('F', drop=False,inplace=True)
df
3、append=True:原来的index不删除
df.set_index('F', append=True, inplace=True)
df
4、reset_index()
还有一个经常用的方法:reset_index()
df.reset_index(inplace=True)
df
去掉原来的index
df.reset_index(drop=True,inplace=True)
df