Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append suffix to a pandas series index

Given the following Panda series:

>>>series = pd.Series([1, 2, 3], index=["a", "b", "c"])
>>>series
a   1
b   2
c   3
dtype: int64

Is there a way to produce this?

>>>series.do_something()
a_x   1
b_x   2
c_x   3
dtype: int64

Background

I have a Series that was produced from a DataFrame aggregate function: df.sum()

The indexes are currently the column names, but I want them to be the column names plus _sum, like so:

>>>data
col1_sum   500.00
col2_sum   9324.0
col3_sum   0.2340
dtype: float64
like image 307
stevendesu Avatar asked Sep 19 '17 18:09

stevendesu


3 Answers

In [49]: series.index += '_sum'

In [50]: series
Out[50]:
a_sum    1
b_sum    2
c_sum    3
dtype: int64
like image 72
MaxU - stop WAR against UA Avatar answered Sep 20 '22 13:09

MaxU - stop WAR against UA


Maybe series.add_suffix('_x') matches what you need!

And series.add_prefix('x_') returns something like this:

x_a    1
x_b    2
x_c    3
dtype: int64
like image 43
Fitz_Hoo Avatar answered Sep 21 '22 13:09

Fitz_Hoo


For completeness, you can use str.replace.

s.index = s.index.str.replace('(.*)', r'\1_sum') 

print(s)
a_sum    1
b_sum    2
c_sum    3
dtype: int64
like image 43
cs95 Avatar answered Sep 20 '22 13:09

cs95