set_axis

To change the index of an existing Series, use set_axis:

x = x.set_axis(index_values)

# 2014-01-01    421
# 2014-01-02    122
# 2014-01-03    275
# 2014-01-04    847
# 2014-01-05    175
# dtype: int64

Advantages over x.index = index_values:

  1. Method chaining

    x.some_method().set_axis(index_values).another_method()
    
  2. Error checking

    x.set_axis(list('abcdefg')) # ValueError: Length mismatch (Series:5, Index:7)
    
    x.index = list('abcdefg') # No error despite mismatch
    

index param

If you're creating a new Series, use the index param at creation time:

x = pd.Series([421, 122, 275, 847, 175], index=index_values)
Answer from tdy on Stack Overflow
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.DataFrame.set_index.html
pandas.DataFrame.set_index โ€” pandas 3.0.3 documentation
>>> df.set_index([pd.Index([1, 2, 3, 4]), "year"]) month sale year 1 2012 1 55 2 2014 4 40 3 2013 7 84 4 2014 10 31 ... >>> s = pd.Series([1, 2, 3, 4]) >>> df.set_index([s, s**2]) month year sale 1 1 1 2012 55 2 4 4 2014 40 3 9 7 2013 84 4 16 10 2014 31
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.index.html
pandas.Series.index โ€” pandas 3.0.3 documentation - PyData |
The index of a Series is used to label and identify each element of the underlying data. The index can be thought of as an immutable ordered set (technically a multi-set, as it may contain duplicate labels), and is used to index and align data in pandas.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.reset_index.html
pandas.Series.reset_index โ€” pandas 3.0.3 documentation
>>> arrays = [ ... np.array(["bar", "bar", "baz", "baz"]), ... np.array(["one", "two", "one", "two"]), ... ] >>> s2 = pd.Series( ... range(4), ... name="foo", ... index=pd.MultiIndex.from_arrays(arrays, names=["a", "b"]), ... ) To remove a specific level from the Index, use level. >>> s2.reset_index(level="a") a foo b one bar 0 two bar 1 one baz 2 two baz 3 ยท If level is not set, all levels are removed from the Index.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ pandas โ€บ python-pandas-series-index
Pandas Series Index Attribute - GeeksforGeeks
July 11, 2025 - Explanation: This code creates a Pandas Series with custom index labels ('a', 'b', 'c', 'd') and retrieves the index using data.index. It then updates the index to ('w', 'x', 'y', 'z'). ... Parameter: This method does not take any parameter. Returns: Index labels of the Series. ... Retrieves the current index labels of the Series. Can be used to set new index labels.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.reindex.html
pandas.Series.reindex โ€” pandas 3.0.3 documentation
The values of the index at the matching locations most satisfy the equation abs(index[indexer] - target) <= tolerance. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the indexโ€™s type.
๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ create index in a pandas series
Create Index in a Pandas Series - PythonForBeginners.com
December 5, 2022 - To modify the original series by assigning new indices instead of creating a new one, you can create an index in place in the series. To create an index inplace in a pandas series, you can assign the new index to the index attribute of the series object as shown in the following example.
๐ŸŒ
Finxter
blog.finxter.com โ€บ 5-best-ways-to-set-index-in-a-pandas-series
5 Best Ways to Set Index in a Pandas Series โ€“ Be on the Right Side of Change
February 19, 2024 - One standard way to set a new index on a pandas Series is by using the set_index() method. This method is straightforward and allows you to set an existing column or a new array as the index.
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-specify-an-index-while-creating-a-series-in-pandas
How to specify an index while creating a Series in Pandas?
November 17, 2021 - Specifying index names can be achieved by assigning a python list (countries list) to the index keyword of the pandas Series function. One thing we should remember here is the length of index data must be the same as the length of series data.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.Series.reset_index.html
pandas.Series.reset_index โ€” pandas 3.0.2 documentation
>>> arrays = [ ... np.array(["bar", "bar", "baz", "baz"]), ... np.array(["one", "two", "one", "two"]), ... ] >>> s2 = pd.Series( ... range(4), ... name="foo", ... index=pd.MultiIndex.from_arrays(arrays, names=["a", "b"]), ... ) To remove a specific level from the Index, use level. >>> s2.reset_index(level="a") a foo b one bar 0 two bar 1 one baz 2 two baz 3 ยท If level is not set, all levels are removed from the Index.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ dev โ€บ reference โ€บ api โ€บ pandas.Series.index.html
pandas.Series.index โ€” pandas 3.0.0.dev0+2416.g10a53051e7 documentation
For more information on pandas indexing, see the indexing user guide. ... >>> cities = ['Kolkata', 'Chicago', 'Toronto', 'Lisbon'] >>> populations = [14.85, 2.71, 2.93, 0.51] >>> city_series = pd.Series(populations, index=cities) >>> city_series.index Index(['Kolkata', 'Chicago', 'Toronto', 'Lisbon'], dtype='object')
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.html
pandas.Series โ€” pandas 3.0.3 documentation
Operations between Series (+, -, /, *, **) align values based on their associated index valuesโ€“ they need not be the same length. The result index will be the sorted union of the two indexes. ... Contains data stored in Series. If data is a dict, argument order is maintained. Unordered sets are ...
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ version โ€บ 2.2.1 โ€บ reference โ€บ api โ€บ pandas.Series.index.html
pandas.Series.index โ€” pandas 2.2.1 documentation
For more information on pandas indexing, see the indexing user guide. ... >>> cities = ['Kolkata', 'Chicago', 'Toronto', 'Lisbon'] >>> populations = [14.85, 2.71, 2.93, 0.51] >>> city_series = pd.Series(populations, index=cities) >>> city_series.index Index(['Kolkata', 'Chicago', 'Toronto', 'Lisbon'], dtype='object')
Top answer
1 of 1
8

I think there is problem with not align index of column data['numerical_column'].

So need convert it to numpy array by values:

new_series = pd.Series(data['numerical_column'].values , index=data['dates'])

Sample:

import pandas as pd
import datetime

data = pd.DataFrame({
'dates': {0: datetime.date(1980, 1, 31), 1: datetime.date(1980, 2, 29), 
          2: datetime.date(1980, 3, 31), 3: datetime.date(1980, 4, 30), 
          4: datetime.date(1980, 5, 31), 5: datetime.date(1980, 6, 30)}, 
'numerical_column': {0: 1, 1: 4, 2: 5, 3: 3, 4: 1, 5: 0}})
print (data)
        dates  numerical_column
0  1980-01-31                 1
1  1980-02-29                 4
2  1980-03-31                 5
3  1980-04-30                 3
4  1980-05-31                 1
5  1980-06-30                 0

new_series = pd.Series(data['numerical_column'].values , index=data['dates'])
print (new_series)
dates
1980-01-31    1
1980-02-29    4
1980-03-31    5
1980-04-30    3
1980-05-31    1
1980-06-30    0
dtype: int64

But method with set_index is nicer, but slowier:

#[60000 rows x 2 columns]
data = pd.concat([data]*10000).reset_index(drop=True)

In [65]: %timeit pd.Series(data['numerical_column'].values , index=data['dates'])
1000 loops, best of 3: 308 ยตs per loop

In [66]: %timeit data.set_index('dates')['numerical_column']
1000 loops, best of 3: 1.28 ms per loop

Verification:

If index of column has same index, it works nice:

s = data.set_index('dates')['numerical_column']
df = s.to_frame()
print (df)
            numerical_column
dates                       
1980-01-31                 1
1980-02-29                 4
1980-03-31                 5
1980-04-30                 3
1980-05-31                 1
1980-06-30                 0

new_series = pd.Series(df['numerical_column'] , index=data['dates'])
print (new_series)
dates
1980-01-31    1
1980-02-29    4
1980-03-31    5
1980-04-30    3
1980-05-31    1
1980-06-30    0
Name: numerical_column, dtype: int64
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.Series.reindex.html
pandas.Series.reindex โ€” pandas 3.0.2 documentation
The values of the index at the matching locations most satisfy the equation abs(index[indexer] - target) <= tolerance. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the indexโ€™s type.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.at.html
pandas.Series.at โ€” pandas 3.0.3 documentation - PyData |
See Fast scalar value getting and setting for more details. ... >>> df = pd.DataFrame( ... [[0, 2, 3], [0, 4, 1], [10, 20, 30]], ... index=[4, 5, 6], ... columns=["A", "B", "C"], ...
๐ŸŒ
Finxter
blog.finxter.com โ€บ 5-best-ways-to-change-index-in-python-pandas-series
5 Best Ways to Change Index in Python Pandas Series โ€“ Be on the Right Side of Change
In this example, set_axis() replaces the index of the series with a new list of labels. The result is a new Series whose index has the labels โ€˜xโ€™, โ€˜yโ€™, and โ€˜zโ€™. While not a direct method to change the index, .loc[] allows for label-based indexing and can be used in a one-liner to assign new values and labels, returning a new Series. ... import pandas as pd # Original Series data = pd.Series([1, 2, 3]) # Using .loc[] to change index and values data = pd.Series(data.values, index=['new_index1', 'new_index2', 'new_index3']) print(data)
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ version โ€บ 2.1.0 โ€บ reference โ€บ api โ€บ pandas.Series.index.html
pandas.Series.index โ€” pandas 2.1.0 documentation - PyData |
For more information on pandas indexing, see the indexing user guide. ... >>> cities = ['Kolkata', 'Chicago', 'Toronto', 'Lisbon'] >>> populations = [14.85, 2.71, 2.93, 0.51] >>> city_series = pd.Series(populations, index=cities) >>> city_series.index Index(['Kolkata', 'Chicago', 'Toronto', 'Lisbon'], dtype='object')
๐ŸŒ
w3resource
w3resource.com โ€บ pandas โ€บ series โ€บ series-reset_index.php
Pandas Series: reset_index() function - w3resource
1 month ago - Example - To update the Series in place, without generating a new one set inplace to True. Note that it also requires drop=True: Python-Pandas Code: import numpy as np import pandas as pd s = pd.Series([2, 3, 4, 5], name='f1', index=pd.Index(['p', 'q', 'r', 's'], name='idx')) s.reset_index(inplace=True, drop=True) s ยท