-1

How do I replace all abbreviation in a column to word eg NY to New York, US to United States etal. I could do for just NY with inplace=True, but I need to collectively do for all abbreviations.

I tried df['prod_state'].replace('NY', 'New York', inplace= True), it worked but when I included US, errors started popping

  • Hi, https://stackoverflow.com/help/minimal-reproducible-example – 404pio Nov 23 '22 at 22:35
  • `pandas.map` can do bulk replacements using a dictionary, if you are matching the entire column. If you need substrings, then there is no way to do it in bulk. – Tim Roberts Nov 23 '22 at 22:37
  • 1
    We love that you're here with us and we don't know what "errors started popping" nor can we reproduce your results. – nicomp Nov 23 '22 at 22:37
  • This should help: https://stackoverflow.com/questions/22100130/pandas-replace-multiple-values-one-column – Swifty Nov 23 '22 at 22:38
  • [The `replace()` docs](https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html) says that the `to_replace` and `value` arguments can be lists of the same length, and elements in the first list will be replaced with the element at the same index in the second list. – Dash Nov 23 '22 at 22:38

1 Answers1

0

You can use pandas.Series.replace that accept dictionnaries as an argument of to_replace:

dico_abbrv= {'NY': 'New York', 'US': 'United States'}

df['prod_state'].replace(dico_abbrv, inplace= True)

You can also use pandas.Series.map :

df['prod_state']= df['prod_state'].map(dico_abbrv)
Timeless
  • 22,580
  • 4
  • 12
  • 30