DataFrame的reset_index函数

notes-pandas-functions

reset_index函数

功能:

示例:

In [1]: df
Out[1]:
          0         1         2         3         4
0 -0.127085 -0.538321  0.641609 -0.020957  0.003503
1 -0.304994  0.157213  0.586962  0.251505  1.022418
2 -0.239710  1.235562  0.917208 -0.964571 -1.120331
3 -0.176416 -0.216204  0.433998 -0.366355 -0.261724

# 删除若干行数据
In [2]: df1 = df.loc[[0,2,3],:]

In [3]: df1
Out[3]:
          0         1         2         3         4
0 -0.127085 -0.538321  0.641609 -0.020957  0.003503
2 -0.239710  1.235562  0.917208 -0.964571 -1.120331
3 -0.176416 -0.216204  0.433998 -0.366355 -0.261724


# reset_index,原行索引作为一列保留,列名为index
In [4]: df2 = df1.reset_index()

In [5]: df2
Out[5]:
   index         0         1         2         3         4
0      0 -0.127085 -0.538321  0.641609 -0.020957  0.003503
1      2 -0.239710  1.235562  0.917208 -0.964571 -1.120331
2      3 -0.176416 -0.216204  0.433998 -0.366355 -0.261724

# reset_index,通过函数 drop=True 删除原行索引
In [6]: df3 = df1.reset_index(drop=True)

In [7]: df3
Out[7]:
          0         1         2         3         4
0 -0.127085 -0.538321  0.641609 -0.020957  0.003503
1 -0.239710  1.235562  0.917208 -0.964571 -1.120331
2 -0.176416 -0.216204  0.433998 -0.366355 -0.261724

你可能感兴趣的:(Python)