Replace the index of a pd.Series

You can’t modify an index, but you can replace it with a new one. Replacing the index does not change the order of the rows in the Series. (To change the order, see reindex, sort_index, or sort_values.)

import sys
import pandas as pd

data = [10.0, 20.0, 30.0, 40.0, 50.0]
series = pd.Series(data = data, name = "temperature") #born with the default index
print(series)
print()

index = pd.RangeIndex(1, len(series) + 1, name = "day")
series.index = index   #Replace the existing index with a new one.
print(series)

sys.exit(0)
0    10.0
1    20.0
2    30.0
3    40.0
4    50.0
Name: temperature, dtype: float64

day
1    10.0
2    20.0
3    30.0
4    40.0
5    50.0
Name: temperature, dtype: float64

Things to try

  1. What happens if the new index is not the same length as the pd.Series?