熊猫重置指数似乎不起作用?

问题描述 投票:14回答:4

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

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

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

这看起来像一个新的索引,但事实并非如此。再次运行test.head,指数仍然相同。尝试使用lambda.applyiterrows()会导致数据帧出现问题。

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

python pandas indexing reset
4个回答
38
投票

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


9
投票

BrenBarn的回答很有效。

以下也通过this thread工作,这不是故障排除,而是关于如何重置索引的清晰度:

test = test.reset_index(drop=True)

1
投票

我会在代码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()

1
投票

作为in code veritas答案的延伸......而不是在最后做del

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

你可以设置下降到True

test = test.reset_index(drop=True)
© www.soinside.com 2019 - 2024. All rights reserved.