如何在熊猫数据框架中重置索引?

我有一个数据框架,从中删除一些行。结果,我得到了一个数据框架,其中的索引是这样的:[1,5,6,10,11],我想把它重置为[0,1,2,3,4]。我该怎么做呢?


以下方法似乎有效:

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

以下选项无效:

df = df.reindex()
871163 次浏览

DataFrame.reset_index是你要找的。如果你不希望它保存为一个列,那么执行:

df = df.reset_index(drop=True)

如果你不想重新分配:

df.reset_index(drop=True, inplace=True)

另一个解决方案是赋值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
data1.reset_index(inplace=True)