Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas reset index is not taking effect [duplicate]

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?

like image 756
Union find Avatar asked Jan 02 '15 01:01

Union find


People also ask

What does pandas reset index do?

pandas. reset_index in pandas is used to reset index of the dataframe object to default indexing (0 to number of rows minus 1) or to reset multi level index. By doing so, the original index gets converted to a column.

How do I reset a DataFrame index?

Use DataFrame.reset_index() function We can use DataFrame. reset_index() to reset the index of the updated DataFrame. By default, it adds the current row index as a new column called 'index' in DataFrame, and it will create a new row index as a range of numbers starting at 0.

Can pandas index repeat?

repeat() function repeat elements of an Index. The function returns a new index where each element of the current index is repeated consecutively a given number of times.


Video Answer


3 Answers

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).

like image 115
BrenBarn Avatar answered Oct 05 '22 20:10

BrenBarn


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)
like image 29
Union find Avatar answered Oct 05 '22 21:10

Union find


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

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

You can set drop to True.

test = test.reset_index(drop=True)
like image 39
Wendao Liu Avatar answered Oct 05 '22 20:10

Wendao Liu