Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset index in a pandas dataframe? [duplicate]

I have a dataframe from which I remove some rows. As a result, I get a dataframe in which index is something like that: [1,5,6,10,11] and I would like to reset it to [0,1,2,3,4]. How can I do it?


The following seems to work:

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

The following does not work:

df = df.reindex() 
like image 505
Roman Avatar asked Dec 10 '13 09:12

Roman


People also ask

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.

How do I reindex in pandas?

One can reindex a single column or multiple columns by using reindex() method and by specifying the axis we want to reindex. Default values in the new index that are not present in the dataframe are assigned NaN.

Can pandas duplicate indexes?

Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated.


1 Answers

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True) 

If you don't want to reassign:

df.reset_index(drop=True, inplace=True) 
like image 80
mkln Avatar answered Sep 28 '22 01:09

mkln