0

I am trying to perform calculations on a huge data frame with column names such as Std 1, Std 2, ..., Std 8760. Given that Python doesn't recognize spaces (' '), I would like to change these names, but using functions such as df.rename or df.replace will either be time-consuming since I will have to specify the new names of all columns or will attribute the same name to all the columns(which I don't want).

Also, I tried using df.columns.str.replace(' ','_') to get rid of the spaces and keeping the names same but I have an output as:

Index([u'_J_a_h_r_', u'_i_d___a_g_s___l_k_', u'_H_o_e_h_e___i_n___m_',
       u'_S_t_d_ _1_', u'_S_t_d_ _2_', u'_S_t_d___1_', u'_S_t_d_ _4_',
       u'_S_t_d_ _5_', u'_S_t_d_ _6_', u'_S_t_d_ _7_',
       ...
       u'_S_t_d_ _8_7_7_5_', u'_S_t_d_ _8_7_7_6_', u'_S_t_d_ _8_7_7_7_',
       u'_S_t_d_ _8_7_7_8_', u'_S_t_d_ _8_7_7_9_', u'_S_t_d_ _8_7_8_0_',
       u'_S_t_d_ _8_7_8_1_', u'_S_t_d_ _8_7_8_2_', u'_S_t_d_ _8_7_8_3_',
       u'_S_t_d___8_7_6_4_'],
      dtype='object', length=8787)

which doesn't solve my issue because I can still see a space in between "Std" and the figure that follows.

Georgy
  • 12,464
  • 7
  • 65
  • 73
vichel
  • 1
  • 2
  • 1
    Can you please paste original dataframe and expected – nithin Dec 12 '19 at 14:19
  • The replace you are doing is not in-place. Possible duplicate of https://stackoverflow.com/questions/11346283/renaming-columns-in-pandas – Afaq Dec 12 '19 at 14:24
  • What do you mean by "python doesn't recognise spaces"? You can use spaces everywhere except for variables' naming. – Oleg O Dec 12 '19 at 14:28

1 Answers1

0

I don't know about the best way to do it, but I would do something like this:

df_cols = df.columns.tolist()
map = str.maketrans({' ':'_'})
new_df_cols = [col.translate(map) for col in df_cols]

df.columns = new_df_cols
Dan White
  • 533
  • 1
  • 8
  • 18