Eugene_Harold
Eugene_Harold

Reputation: 523

How do I change the index values of a Pandas Series?

How can I change the index values of a Pandas Series from the regular integer value that they default to, to values within a list that I have? e.g.

x = pd.Series([421, 122, 275, 847, 175])

index_values = ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04',
               '2014-01-05'] 

How do I get the dates in the index_values list to be the indexes in the Series that I've created?

Upvotes: 40

Views: 44966

Answers (2)

tdy
tdy

Reputation: 41327

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)

Upvotes: 49

jezrael
jezrael

Reputation: 862641

You can assign index values by list:

x.index = index_values
print(x)
2014-01-01    421
2014-01-02    122
2014-01-03    275
2014-01-04    847
2014-01-05    175
dtype: int64

Upvotes: 16

Related Questions