简体   繁体   English

如何在 dropna() pandas dataframe 后重置索引 pandas dataframe

[英]how to reset index pandas dataframe after dropna() pandas dataframe

I'm not sure how to reset index after dropna() .我不确定如何在dropna()之后重置索引。 I have我有

df_all = df_all.dropna()
df_all.reset_index(drop=True)

but after running my code, row index skips steps.但在运行我的代码后,行索引会跳过步骤。 For example, it becomes 0,1,2,4,...比如变成0,1,2,4,...

The code you've posted already does what you want, but does not do it "in place." 您发布的代码已经按照您的要求执行,但不会“就位”。 Try adding inplace=True to reset_index() or else reassigning the result to df_all . 尝试将reset_index() inplace=True添加到reset_index()或者将结果重新分配给df_all Note that you can also use inplace=True with dropna() , so: 请注意,您还可以使用带有dropna() inplace=True ,因此:

df_all.dropna(inplace=True)
df_all.reset_index(drop=True, inplace=True)

Does it all in place. 这一切都到位了。 Or, 要么,

df_all = df_all.dropna()
df_all = df_all.reset_index(drop=True)

to reassign df_all . 重新分配df_all

You can chain methods and write it as a one-liner:您可以链接方法并将其编写为单行代码:

df = df.dropna().reset_index(drop=True)

You can reset the index to default using set_axis() as well.您也可以使用set_axis()将索引重置为默认值。

df.dropna(inplace=True)
df.set_axis(range(len(df)), inplace=True)

set_axis() is especially useful, if you want to reset the index to something other than the default because as long as the lengths match, you can change the index to literally anything with it. set_axis()特别有用,如果你想将索引重置为默认值以外的值,因为只要长度匹配,你就可以将索引更改为任何字面意思。 For example, you can change it to first row , second row etc.例如,您可以将其更改为first rowsecond row等。

df = df.dropna()
df = df.set_axis(['first row', 'second row'])

资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM