【问题标题】:In Python pandas, start row index from 1 instead of zero without creating additional column在 Python pandas 中,从 1 而不是 0 开始行索引而不创建额外的列
【发布时间】:2015-11-21 20:53:24
【问题描述】:

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

df.reset_index(inplace=True)

但这将从0 开始索引。我想从1开始。如何在不创建任何额外列并保留 index/reset_index 功能和选项的情况下做到这一点?我确实想创建一个新的数据框,所以inplace=True 应该仍然适用。

【问题讨论】:

    标签: python pandas indexing dataframe


    【解决方案1】:

    为此,您可以执行以下操作(我创建了一个示例数据框):

    price_of_items = pd.DataFrame({
    "Wired Keyboard":["$7","4.3","12000"],"Wireless Keyboard":["$13","4.6","14000"]
                                 })
    price_of_items.index += 1
    

    【讨论】:

      【解决方案2】:

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

      #df.index
      

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

      您可以像这样指定任何起始值范围:

      df.index = pd.RangeIndex(start=1, stop=600, step=1)
      

      参考:pandas.RangeIndex

      【讨论】:

        【解决方案3】:

        直接分配一个新的索引数组即可:

        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 会更快

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-07-05
          • 2023-03-30
          • 1970-01-01
          • 2011-02-17
          • 2020-09-18
          • 2019-09-05
          • 2021-05-27
          相关资源
          最近更新 更多