在Python pandas中,从1而不是零开始行索引而不创建其他列

Bra*_*roy 24 python indexing dataframe pandas

我知道我可以像这样重置索引

df.reset_index(inplace=True)
Run Code Online (Sandbox Code Playgroud)

但这将从索引开始0.我想从它开始1.如何在不创建任何额外列且保留index/reset_index功能和选项的情况下执行此操作?我希望创建一个新的数据帧,所以inplace=True应该仍然适用.

EdC*_*ica 49

只需直接分配一个新的索引数组:

df.index = np.arange(1, len(df) + 1)
Run Code Online (Sandbox Code Playgroud)

例:

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
Run Code Online (Sandbox Code Playgroud)

要不就:

df.index = df.index + 1
Run Code Online (Sandbox Code Playgroud)

如果索引已经基于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
Run Code Online (Sandbox Code Playgroud)

因此,如果没有reset_index我无法明确说明的时机,那么如果索引已经0基于,那么只需在每个索引值中添加1就会更快


hak*_*ode 6

您还可以使用如下所示的索引范围指定起始值。Pandas 支持 RangeIndex。

#df.index
Run Code Online (Sandbox Code Playgroud)

打印默认值,(start=0,stop=lastelement, step=1)

您可以指定任何起始值范围,如下所示:

df.index = pd.RangeIndex(start=1, stop=600, step=1)
Run Code Online (Sandbox Code Playgroud)

参考:pandas.RangeIndex