Home >Backend Development >Python Tutorial >How do I reset the index of a Pandas DataFrame after removing rows?

How do I reset the index of a Pandas DataFrame after removing rows?

DDD
DDDOriginal
2024-10-29 00:39:02772browse

How do I reset the index of a Pandas DataFrame after removing rows?

Method to Reset Index in a Pandas Dataframe

Resetting the index of a dataframe can be necessary when you remove rows and want to keep a continuous index. In this case, you may encounter the problem of having an irregular index such as [1, 5, 6, 10, 11]. To remedy this, pandas provides a convenient solution with the DataFrame.reset_index method.

Example:

Consider the following dataframe with an irregular index:

<code class="python">import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 9], 'b': [2, 4, 6, 8, 10]}, index=[1, 5, 6, 10, 11])</code>

Solution:

To reset the index, use the reset_index method:

<code class="python">df = df.reset_index()</code>

This will create a new column named 'index' with the original index values. To remove this column, use the drop parameter:

<code class="python">df = df.reset_index(drop=True)</code>

Now, the dataframe will have a continuous index starting from 0:

<code class="python">print(df)

   a  b
0  1  2
1  3  4
2  5  6
3  7  8
4  9 10</code>

Alternative Method:

Instead of reassigning the dataframe, you can use the inplace parameter to modify it directly:

<code class="python">df.reset_index(drop=True, inplace=True)</code>

Note: Using the reindex method will not reset the index of the dataframe.

The above is the detailed content of How do I reset the index of a Pandas DataFrame after removing rows?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn