reset_index()主要用于重置索引
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(9).reshape(3,3),index=[1,3,4])
print(df)
0 1 2
1 0 1 2
3 3 4 5
4 6 7 8
reset_index()重置索引
print(df.reset_index())
index 0 1 2
0 1 0 1 2
1 3 3 4 5
2 4 6 7 8
在获得新的index,原来的index变成数据列,保留在数据框中,不想保留原来的index的话可以使用参数drop=True,默认False。
print(df.reset_index(drop=True))
0 1 2
0 0 1 2
1 3 4 5
2 6 7 8
另外在保留的index时,可以直接用rename()函数修改index列的列名:
print(df.reset_index().rename(columns={"index":"new"}))
new 0 1 2
0 1 0 1 2
1 3 3 4 5
2 4 6 7 8