Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

reset_index

By default reset_index returns a copy rather than modify the original data frame. You can specify inplace = True to overwrite the behavior.

Series

  1. If you drop the original index, you still have a Series. However, if you reset index of a sereis without dropping the original index, you get a data frame.

s = pd.Series([1, 2, 3, 4], index=["r1", "r2", "r3", "r4"])
s
r1 1 r2 2 r3 3 r4 4 dtype: int64
df = s.reset_index()
df
Loading...
df = s.reset_index(drop=True)
df
0 1 1 2 2 3 3 4 dtype: int64

DataFrame

import pandas as pd

df = pd.DataFrame(
    {"x": [1, 2, 3, 4, 5], "y": [5, 4, 3, 2, 1]}, index=["r1", "r2", "r3", "r4", "r5"]
)

df.head()
Loading...
# keep the original index as a new column and create a new index
df.reset_index()
Loading...
# drop the original index and create a new index
df.reset_index(drop=True)
Loading...

Multi-index

import pandas as pd

df = pd.DataFrame(
    {"x": [1, 2, 3, 4, 5], "y": [5, 4, 3, 2, 1]},
    index=pd.MultiIndex.from_tuples(
        [("r1", 0), ("r2", 1), ("r3", 2), ("r4", 3), ("r5", 4)]
    ),
)

df.head()
Loading...
df.reset_index()
Loading...
df.reset_index(drop=True)
Loading...
# drops the 2nd index and keep the first index
df.reset_index(level=1, drop=True)
Loading...