-1

I want to replace symbols in dataframe headings by using data.columns.str.replace(' ', '_', inplace=True) I received error TypeError: replace() got an unexpected keyword argument 'inplace'

Also I tried to replace multiple symbols in one line data.columns.str.replace([' ', ' - '], '_') I received error TypeError: unhashable type: 'list'

This one works, data.columns.str.replace(' ', '_') but ideally I want to replace multiple symbols in headings at once.

Osca
  • 1,588
  • 2
  • 20
  • 41
  • You have not provided any samples for us to work with. How can we recreate and help you with an issue if we have no clue what you are working with. Please read [this](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) on how to post a good, reproducible question. – Ukrainian-serge Mar 18 '20 at 01:53

2 Answers2

1

you need to reassign as inplace is not a parameter and you can concatenate the symbols you want to replace with | like:

df.columns = df.columns.str.replace(' |-', '_')
Ben.T
  • 29,160
  • 6
  • 32
  • 54
  • Thank you Ben. I read that `inplace` is a parameter here https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html. I'm confused – Osca Mar 18 '20 at 01:56
  • 2
    @Osca check the doc again , https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html, str.replace do not have inplace – BENY Mar 18 '20 at 01:57
  • 1
    @Osca the link you gave is to use `replace` on the values in a dataframe, your question is on the columns' name, that use the `str.replace` method that YOBEN_S gave the link – Ben.T Mar 18 '20 at 02:01
0

Not sure if it's the best way to do it, but if you want to use replace for strings and make the change in-place, you could generate a dictionary argument for the df.rename() method:

# Dummy dataframe
data = {'A heading': [1,4,7,9], 'B - Heading': [2, 4, 3, 1]}
df = pd.DataFrame(data)

# Create a list of the new columns using list comprehension and .replace()
new_cols = [h.replace(' - ','_').replace(' ', '_') for h in df.columns]

# Pack into a dictionary with old columns as keys and new columns as values
replace_dict = dict(zip(df.columns, new_cols))
replace_dict

# Use the .rename() method to rename in place
df.rename(columns=replace_dict, inplace=True)