0

In pandas I am calculating means of columns and I want to rename the columns appending the string _avg.

Following the example in the answer here works: so if I do:

ss = df[col_list].mean()
ss.index = [el+"_avg" for el in col_list]

But although df[col_list].mean() is a pandas.Series type doing:

ss = df[col_list].mean().index = [el+"_avg" for el in col_list]

returns a list of strings and

ss = pandas.Series(df[col_list].mean().index = [el+"_avg" for el in col_list])

is not working at all while as in the previous link

ss = pandas.Series(df[col_list].mean(), index= [el+"_avg" for el in col_list])

changes the names but the values become NaN. (This behaviour is actually explained in the doc)

Why is that and how can I merge the two expressions a single line?

roschach
  • 8,390
  • 14
  • 74
  • 124
  • `x = y.index = z` does `x = z` and then `y.index = x`. It doesn't do `x = y` and then `y.index = z`. – TigerhawkT3 Jan 23 '19 at 17:48
  • C.f. https://stackoverflow.com/questions/7601823/how-do-chained-assignments-work and https://stackoverflow.com/questions/11498441/what-is-this-kind-of-assignment-in-python-called-a-b-true. – TigerhawkT3 Jan 23 '19 at 17:50
  • Actually I am doing `x = new_type(y.index=z)` am I not? – roschach Jan 23 '19 at 17:56
  • Nope. Assignment chaining is kinda funny. Using multiple lines for multiple simple assignments is generally clearer and easier to read for this reason. – TigerhawkT3 Jan 23 '19 at 18:02

2 Answers2

2

You could use the add_suffix method:

ss = df[col_list].mean().add_suffix('_avg')

For example,

In [75]: ss = pd.Series([1,2,3], list('ABC'))

In [76]: ss.add_suffix('_avg')
Out[76]: 
A_avg    1
B_avg    2
C_avg    3
dtype: int64

There is also an add_prefix method:

In [77]: ss.add_prefix('col_')
Out[77]: 
col_A    1
col_B    2
col_C    3
dtype: int64
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

Have you tried to extract the values from the series?

ss = pandas.Series(df[col_list].mean().values, index= [el+"_avg" for el in col_list])
nick
  • 1,310
  • 8
  • 15