Python 熊猫重置索引似乎不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27736267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:11:57  来源:igfitidea点击:

Pandas reset index doesn't seem to work?

pythonpandasindexingreset

提问by Learning stats by example

I'm not sure where I am astray but I cannot seem to reset the index on a dataframe.

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

When I run test.head(), I get the output below:

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

test.head

测试头

As you can see, the dataframe is a slice, so the index is out of bounds. What I'd like to do is to reset the index for this dataframe. So I run test.reset_index(drop=True). This outputs the following:

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

reset

重启

That looks like a new index, but it's not. Running test.headagain, the index is still the same. Attempting to use lambda.applyor iterrows()creates problems with the dataframe.

这看起来像是一个新索引,但事实并非如此。test.head再次运行,索引还是一样。尝试使用数据框lambda.applyiterrows()创建数据框问题。

How can I really reset the index?

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

采纳答案by Learning stats by example

BrenBarn's answer works.

布伦巴恩的回答有效。

The following also worked via this thread, which isn't a troubleshooting so much as an articulation of how to reset the index:

以下内容也通过此线程工作,这与其说是故障排除,不如说是说明如何重置索引:

test = test.reset_index(drop=True)

回答by BrenBarn

reset_indexby default does not modify the DataFrame; it returns a newDataFrame with the reset index. If you want to modify the original, use the inplaceargument: df.reset_index(drop=True, inplace=True). Alternatively, assign the result of reset_indexby doing df = df.reset_index(drop=True).

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

回答by Subspacian

I would add to in code veritas's answer:

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

If you already have an index column specified, then you can save the del, of course. In my hypothetical example:

如果您已经指定了索引列,那么您当然可以保存 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()

回答by Wendao Liu

As an extension of in code veritas's answer... instead of doing delat the end:

作为代码 veritas答案的扩展......而不是del在最后做:

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

You can set drop to True.

您可以将 drop 设置为True.

test = test.reset_index(drop=True)