Pandas: Change index of series while chaining

Viewed 72

Suppose I have a Pandas series

>>> s = pd.Series([1,2,3])
0 | 1
1 | 2
2 | 3

I can change the index by

>>> s.index = ['a', 'b', 'c']
a | 1
b | 2
c | 3

but how do I do this while chaining, like

s.apply(some_fun).<reindex to letters>.combine(...).etc.
2 Answers

Use Series.set_axis:

s = pd.Series([1,2,3])
s = s.set_axis(['a', 'b', 'c'])

print (s)
a    1
b    2
c    3
dtype: int64

There's a rename:

new_idx = ['a','b','c']
s.rename(dict(zip(s.index, new_idx)))

Out:

a    1
b    2
c    3
dtype: int64
Related