How to reset index in a pandas data frame?
我有一个数据帧,从中删除一些行。因此,我得到了一个数据帧,其中索引类似于:
以下内容似乎有效:
1 2 | df = df.reset_index() del df['index'] |
以下内容不起作用:
1 | df = df.reindex() |
你要找的是
1 | df = df.reset_index(drop=True) |
另一种解决方案是分配
1 2 3 | df.index = pd.RangeIndex(len(df.index)) df.index = range(len(df.index)) |
速度更快:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |
1 | data1.reset_index(inplace=True) |