如何重置pandas数据帧中的索引?

时间:2013-12-10 09:12:56

标签: python indexing pandas dataframe

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


以下似乎有效:

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

以下不起作用:

df = df.reindex()

3 个答案:

答案 0 :(得分:505)

reset_index()正是您要找的。如果您不希望将其另存为列,请执行以下操作:

df = df.reset_index(drop=True)

答案 1 :(得分:32)

另一种解决方案是分配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

答案 2 :(得分:6)

data1.reset_index(inplace=True)