pandas中dataframe重置索引在pandas中,自定义索引后,有时候又需要恢复默认索引。import pandas as pdimport numpy as npdf = pd.datafr
pandas中dataframe重置索引
在pandas中,自定义索引后,有时候又需要恢复默认索引。
import pandas as pd
import numpy as np
df = pd.dataframe(np.arange(20).reshape(5,4),columns=['a','b','c','d'])
df
| a | b | c | d |
|---|
| 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 |
|---|
# 对df重排顺序,得到索引顺序倒序的数据
df = df.sort_values('a',ascending=false)
df
| a | b | c | d |
|---|
| 4 | 16 | 17 | 18 | 19 |
|---|
| 3 | 12 | 13 | 14 | 15 |
|---|
| 2 | 8 | 9 | 10 | 11 |
|---|
| 1 | 4 | 5 | 6 | 7 |
|---|
| 0 | 0 | 1 | 2 | 3 |
|---|
一、根据数据行的个数重新赋予索引
df.index = range(len(df))
df
| a | b | c | d |
|---|
| 0 | 16 | 17 | 18 | 19 |
|---|
| 1 | 12 | 13 | 14 | 15 |
|---|
| 2 | 8 | 9 | 10 | 11 |
|---|
| 3 | 4 | 5 | 6 | 7 |
|---|
| 4 | 0 | 1 | 2 | 3 |
|---|
二、使用reset_index(drop=true)
drop=true表示删除原索引,不然会在数据表格中新生成一列’index’数据
| index | a | b | c | d |
|---|
| 0 | 4 | 16 | 17 | 18 | 19 |
|---|
| 1 | 3 | 12 | 13 | 14 | 15 |
|---|
| 2 | 2 | 8 | 9 | 10 | 11 |
|---|
| 3 | 1 | 4 | 5 | 6 | 7 |
|---|
| 4 | 0 | 0 | 1 | 2 | 3 |
|---|
df = df.reset_index(drop=true)
df
| a | b | c | d |
|---|
| 0 | 16 | 17 | 18 | 19 |
|---|
| 1 | 12 | 13 | 14 | 15 |
|---|
| 2 | 8 | 9 | 10 | 11 |
|---|
| 3 | 4 | 5 | 6 | 7 |
|---|
| 4 | 0 | 1 | 2 | 3 |
|---|
三、使用reindex(labels=range(len(df))
df = df.reindex(labels=range(len(df)))
df
| a | b | c | d |
|---|
| 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 |
|---|
四、使用set_index()自定义索引
将原数据集中的列作为索引。
drop=true,默认,是将数据作为索引后,在表格中删除原数据
append=false,默认,是将新设置的索引设置为内层索引,原索引是外层索引
df = df.set_index(keys=['a'])
df
| b | c | d |
|---|
| a | | | |
|---|
| 16 | 17 | 18 | 19 |
|---|
| 12 | 13 | 14 | 15 |
|---|
| 8 | 9 | 10 | 11 |
|---|
| 4 | 5 | 6 | 7 |
|---|
| 0 | 1 | 2 | 3 |
|---|
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
相关文章:
-
-
-
在python中,列表(list)是一种用于存储元素的有序集合,支持索引、切片、增加、删除和排序等操作。下面将详细介绍如何从索引到增删排序系统地理解和操作python列表。1.列表…
-
-
-
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论