Pandas reset index doesn't seem to work?

Learning stats by example picture Learning stats by example · Jan 2, 2015 · Viewed 42.8k times · Source

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

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:

reset

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

How can I really reset the index?

Answer

BrenBarn picture BrenBarn · Jan 2, 2015

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