pandas dataframe index 操作

在操作数据过程中,比如对DataFrame数据,使用sort_values() 函数进行了重排,这个时候,index 也发生了错误,需要我们删除旧的index并生成新的index

这个时候,可以使用 df.reset_index(drop=True) 来完成。

这里,学习列举了更多index 操作:

准备一个原始的data

data = pd.DataFrame({'x1': range(10, 18),     # Create pandas DataFrame
                     'x2': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
                     'x3': range(8, 0, - 1)},
                    index=[5, 6, 2, 1, 4, 7, 0, 3])
print(data)                                  # Print pandas DataFrame

输出如下:

   x1 x2  x3
5  10  a   8
6  11  b   7
2  12  c   6
1  13  d   5
4  14  e   4
7  15  f   3
0  16  g   2
3  17  h   1

1,reindex() 重新排序,保留旧的index 序号,只是打乱了顺序

new_index = [1, 6, 2, 7, 0, 3, 5, 4]         # Create list for new index
print(new_index)
# [1, 6, 2, 7, 0, 3, 5, 4]
# reindx() 函数,是根据你给出的索引list 顺序,把旧的对应index 按照你新给出的顺序排序。
# 你可以根据旧的序列号,把 1号排在第一位,6号排在第二位,2号排在第三位,7号排在第四位
# 等等,依次类推
data_new1 = data.reindex(new_index)          # Apply reindex function
print(data_new1)                             # Print updated DataFrame

输出如下:

[1, 6, 2, 7, 0, 3, 5, 4]
   x1 x2  x3
1  13  d   5
6  11  b   7
2  12  c   6
7  15  f   3
0  16  g   2
3  17  h   1
5  10  a   8
4  14  e   4

2,ort_index() 根据index 列,对df 进行重新排序

data_new2 = data.sort_index()                # Apply sort_sindex function
print(data_new2)                             # Print updated DataFrame

输出如下:

   x1 x2  x3
0  16  g   2
1  13  d   5
2  12  c   6
3  17  h   1
4  14  e   4
5  10  a   8
6  11  b   7
7  15  f   3

3,   reset_index() 重新生成index序列

data_new3 = data.reset_index(drop=True)    # Apply reset_index function, drop=False时, 保留旧的索引为index列
print(data_new3)                             # Print updated DataFrame

print(data_new3.reset_index())              # drop=False时, 保留旧的索引为index列
print(data_new3.set_index(['x3'], inplace=False))   # 将df 某一列作为 index,删除旧的index列

输出如下:

   x1 x2  x3
0  10  a   8
1  11  b   7
2  12  c   6
3  13  d   5
4  14  e   4
5  15  f   3
6  16  g   2
7  17  h   1
   index  x1 x2  x3
0      0  10  a   8
1      1  11  b   7
2      2  12  c   6
3      3  13  d   5
4      4  14  e   4
5      5  15  f   3
6      6  16  g   2
7      7  17  h   1
    x1 x2
x3       
8   10  a
7   11  b
6   12  c
5   13  d
4   14  e
3   15  f
2   16  g
1   17  h

猜你喜欢

转载自blog.csdn.net/abbcccdde/article/details/125748645