how to reset index pandas dataframe after dropna() pandas dataframe

Question:

I’m not sure how to reset index after 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,…

Asked By: JPC

||

Answers:

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. Note that you can also use inplace=True with dropna(), so:

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.

Answered By: John Zwinck

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.

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. For example, you can change it to first row, second row etc.

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

res

Answered By: cottontail
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.