Methods for Working with Index and Position
Every Series contains an index for its values. These methods help us work with that index.
reset_index(): The reset_index() method resets the existing index and creates a new default integer index.
For example:
marks = pd.Series([85, 90, 75], index=["A", "B", "C"])
marks.reset_index()
output:
index 0
0 A 85
1 B 90
2 C 75
By default, the old index is retained as a column in the resulting DataFrame.
If we do not want to keep the old index, we can use:
marks.reset_index(drop=True)
output:
0 85
1 90
2 75
dtype: int64
set_axis(): The set_axis() method changes the labels of the Series index.
For example:
marks = pd.Series([85, 90, 75])
marks.set_axis(["A", "B", "C"])
output:
A 85
B 90
C 75
dtype: int64
Here, the existing index labels are replaced with the given labels.
reindex(): The reindex() method changes the index according to the labels we provide.
For example:
marks = pd.Series([85, 90, 75], index=["A", "B", "C"])
marks.reindex(["A", "C", "D"])
output:
A 85.0
C 75.0
D NaN
dtype: float64
Here, the requested index D does not exist in the original Series, so Pandas places a missing value (NaN) for that index.
take(): The take() method returns elements based on their positional indexes.
For example:
marks = pd.Series([85, 90, 75, 95])
marks.take([0, 2])
output:
0 85
2 75
dtype: int64
Here, Pandas returns the values at positions 0 and 2.