python之pandas中DataFrame重置索引的几种示例
内容摘要
这篇文章主要为大家详细介绍了python之pandas中DataFrame重置索引的几种示例,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随php教程的雯雯来看看吧!
在p
感兴趣的小伙伴,下面一起跟随php教程的雯雯来看看吧!
在p
文章正文
这篇文章主要为大家详细介绍了python之pandas中DataFrame重置索引的几种示例,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随php教程的雯雯来看看吧!
在pandas中,经常对数据进行处理 而导致数据索引顺序混乱,从而影响数据读取、插入等。
小笔总结了以下几种重置索引的方法:
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <code> 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 # 对其重排顺序,得到索引顺序倒序的数据 df2 = df.sort_values( 'a' , ascending=False) # 得到df2: 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 </code> |
pandas中DataFrame重置索引的几种方法
下面对df2重置索引,使其索引从0开始
法一:
简单粗暴:
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | <code> df2.index = range(len(df2)) # 输出df2: 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 </code> |
pandas中DataFrame重置索引的几种方法
法二:
代码如下:
1 2 3 4 5 6 7 8 9 10 | <code> df2 = df2.reset_index(drop=True) # drop=True表示删除原索引,不然会在数据表格中新生成一列 'index' 数据 # 输出df2: 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 </code> |
pandas中DataFrame重置索引的几种方法
法三:
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <code> df2 = df2.reindex(labels=range(len(df)) #labels是第一个参数,可以省略 # 输出df2 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 # 注:df = df.reindex(index=[]),在原数据结构上新建行(index是新索引,若新建数据索引在原数据中存在,则引用原有数据),默认用NaN填充(使用fill_value=0 来修改填充值自定义,此处我设置的是0)。 # df = df.reindex(columns=[]),在原数据结构上新建列,方法与新建行一样 </code> |
pandas中DataFrame重置索引的几种方法
法四:
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <code> df2 = df2.set_index(keys=[ 'a' , 'c' ]) # 将原数据a, c列的数据作为索引。 # drop=True,默认,是将数据作为索引后,在表格中删除原数据 # append=False,默认,是将新设置的索引设置为内层索引,原索引是外层索引 # 输出df2,注意a,c列是索引: b d a c 16 18 17 19 12 14 13 15 8 10 9 11 4 6 5 7 0 2 1 3 </code> |
pandas中DataFrame重置索引的几种方法
到此这篇关于pandas中DataFrame重置索引的几种方法的文章就介绍到这了,更多相关pandas DataFrame重置索引内容请搜索php教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持php教程!
注:关于python之pandas中DataFrame重置索引的几种示例的内容就先介绍到这里,更多相关文章的可以留意
代码注释