6

I want to replace values in a pandas Series using a dictionary. I'm following @DSM's accepted answer like so:

s = Series(['abc', 'abe', 'abg'])
d = {'b': 'B'}
s.replace(d)

But this has no effect:

0    abc
1    abe
2    abg
dtype: object

The documentation explains the required format of the dictionary for DataFrames (i.e. nested dicts with top level keys corresponding to column names) but I can't see anything specific for Series.

semblable
  • 767
  • 8
  • 24
joga
  • 187
  • 1
  • 3
  • 10

1 Answers1

7

You can do it using regex=True parameter:

In [37]: s.replace(d, regex=True)
Out[37]:
0    aBc
1    aBe
2    aBg
dtype: object

As you have already found out yourself - it's a RegEx replacement and it won't work as you expected:

In [36]: s.replace(d)
Out[36]:
0    abc
1    abe
2    abg
dtype: object

this is working as expected:

In [38]: s.replace({'abc':'ABC'})
Out[38]:
0    ABC
1    abe
2    abg
dtype: object
Community
  • 1
  • 1
MaxU - stop genocide of UA
  • 191,778
  • 30
  • 340
  • 375