Append suffix to a pandas series index

Question:

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
Asked By: stevendesu

||

Answers:

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

In [50]: series
Out[50]:
a_sum    1
b_sum    2
c_sum    3
dtype: int64

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
Answered By: cs95

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
Answered By: Fitz_Hoo

In case anyone is curious about using this for a DataFrame, the snippet below accomplishes the task.

Where df is a pandas DataFrame and ‘C_’ is the desired prefix.

The default behavior of add_prefix for a DataFrame is to add the prefix to the columns. Thus the transpose and then add_prefix and then transpose back.

df = df.T.add_prefix(‘C_’).T

Answered By: Robert Calvert
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.