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¶
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"])
sr1 1
r2 2
r3 3
r4 4
dtype: int64df = s.reset_index()
dfLoading...
df = s.reset_index(drop=True)
df0 1
1 2
2 3
3 4
dtype: int64DataFrame¶
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...