我知道我可以像这样重置索引
df.reset_index(inplace=True)
但这将从索引开始0
。我想从开始1
。如何在不创建任何额外列的情况下并通过保留index / reset_index功能和选项来做到这一点?我不希望创建一个新的数据帧,所以inplace=True
应该仍然适用。
只需直接分配一个新的索引数组:
df.index = np.arange(1, len(df) + 1)
例:
In [151]:
df = pd.DataFrame({'a':np.random.randn(5)})
df
Out[151]:
a
0 0.443638
1 0.037882
2 -0.210275
3 -0.344092
4 0.997045
In [152]:
df.index = np.arange(1,len(df)+1)
df
Out[152]:
a
1 0.443638
2 0.037882
3 -0.210275
4 -0.344092
5 0.997045
要不就:
df.index = df.index + 1
如果索引已经基于0
时间安排
由于某些原因,我无法进行计时,reset_index
但以下是100,000行df上的计时:
In [160]:
%timeit df.index = df.index + 1
The slowest run took 6.45 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 107 µs per loop
In [161]:
%timeit df.index = np.arange(1, len(df) + 1)
10000 loops, best of 3: 154 µs per loop
因此,没有时间,reset_index
我无法确切地说,但是如果索引已经0
基于,则将每个索引值加1看起来会更快
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句