【问题标题】:Pandas reset index is not taking effect [duplicate]熊猫重置索引未生效[重复]
【发布时间】:2015-02-28 10:29:30
【问题描述】:

我不确定我在哪里误入歧途,但我似乎无法重置数据帧上的索引。

当我运行test.head() 时,我得到以下输出:

如您所见,数据框是一个切片,因此索引超出范围。 我想做的是重置这个数据框的索引。所以我运行test.reset_index(drop=True)。这将输出以下内容:

这看起来像是一个新索引,但实际上不是。再次运行test.head,索引还是一样的。尝试使用 lambda.applyiterrows() 会导致数据框出现问题。

我怎样才能真正重置索引?

【问题讨论】:

  • 我很抱歉,但那些桌子......如此......如此巨大的图像。 @_@ 我快崩溃了。
  • @kuanb 你会很高兴知道表格在 Jupyter notebook 5 中被重新格式化:)
  • 将数据作为图像发布是违反 SO 准则的,请用数据作为文本重写。

标签: python pandas dataframe indexing reset


【解决方案1】:

reset_index默认不修改DataFrame;它返回一个带有重置索引的 new DataFrame。如果要修改原始文件,请使用inplace 参数:df.reset_index(drop=True, inplace=True)。或者,通过执行 df = df.reset_index(drop=True) 分配reset_index 的结果。

【讨论】:

    【解决方案2】:

    BrenBarn 的 answer 工作。

    以下内容也通过this thread 工作,与其说是故障排除,不如说是如何重置索引:

    test = test.reset_index(drop=True)
    

    【讨论】:

      【解决方案3】:

      我会在代码中添加 veritas 的答案:

      如果您已经指定了索引列,那么您当然可以保存 del。在我的假设示例中:

          df_total_sales_customers = pd.DataFrame({'Sales': total_sales_customers['Sales'],
                                    'Customers': total_sales_customers['Customers']}, index = total_sales_customers.index)
      
          df_total_sales_customers = df_total_sales_customers.reset_index()
      

      【讨论】:

        【解决方案4】:

        作为in code veritas's answer的扩展......而不是在最后做del

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

        您可以将 drop 设置为True

        test = test.reset_index(drop=True)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-12
          • 2020-11-12
          • 2019-07-28
          • 2020-03-24
          • 2020-06-30
          • 2021-03-15
          相关资源
          最近更新 更多