首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在熊猫数据帧中重置索引?

如何在熊猫数据帧中重置索引?
EN

Stack Overflow用户
提问于 2013-12-10 17:12:56
回答 3查看 696.9K关注 0票数 442

我有一个数据帧,我从其中删除了一些行。结果,我得到了一个数据帧,其中的索引类似于:[1,5,6,10,11],我想将其重置为[0,1,2,3,4]。我该怎么做呢?

下面的方法似乎是可行的:

df = df.reset_index()
del df['index']

以下内容不起作用:

df = df.reindex()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-10 18:19:52

DataFrame.reset_index就是你要找的东西。如果不想将其另存为列,请执行以下操作:

df = df.reset_index(drop=True)

如果您不想重新分配:

df.reset_index(drop=True, inplace=True)
票数 901
EN

Stack Overflow用户

发布于 2017-08-15 19:40:58

另一种解决方案是分配RangeIndexrange

df.index = pd.RangeIndex(len(df.index))

df.index = range(len(df.index))

它更快:

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())

In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop

In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop

In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop
票数 59
EN

Stack Overflow用户

发布于 2018-11-23 02:46:32

data1.reset_index(inplace=True)
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20490274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档