当我们在数据清洗去除空值的行或者切分的时候,此时DataFrame或Series类型的数据索引不在是从0开始的索引,这样我们就需要用到reset_index()重置索引。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(40).reshape(10,4),index=[for i in range(0,20,2)])
print(df)
0 1 2 3
0 0 1 2 3
2 4 5 6 7
4 8 9 10 11
6 12 13 14 15
8 16 17 18 19
10 20 21 22 23
12 24 25 26 27
14 28 29 30 31
16 32 33 34 35
18 36 37 38 39
使用reset_index()重置索引
print(df.reset_index())
我们看到我们原来的索引被保留了下来
index 0 1 2 3
0 0 0 1 2 3
1 2 4 5 6 7
2 4 8 9 10 11
3 6 12 13 14 15
4 8 16 17 18 19
5 10 20 21 22 23
6 12 24 25 26 27
7 14 28 29 30 31
8 16 32 33 34 35
9 18 36 37 38 39
print(df.reset_index(drop=True))
我们在df.reset_index()加上drop=True不保留原来的index
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19
5 20 21 22 23
6 24 25 26 27
7 28 29 30 31
8 32 33 34 35
9 36 37 38 39