9

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.

4
  • 3
    you need to assign back the result or pass param inplace=True e.g. s = s.replace(d) or s.replace(d, inplace=True), virtually all pandas ops return a copy so you either want to assign back or pass inplace=True where supported Commented Oct 16, 2016 at 20:29
  • Try this: s.replace(d, regex=True) Commented Oct 16, 2016 at 20:30
  • @EdChum, s.replace(d, inplace=True) - doesn't do desired replacement - test it... Commented Oct 16, 2016 at 20:32
  • 2
    @MaxU That worked - thanks. Hidden assumption - I was looking for regex matching - not exact matching. Didn't realise it myself. Commented Oct 16, 2016 at 20:40

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

2 Comments

Because then it assumes you want to replace the value "b" with "B", but the value b is not in the Series. However, b is contained within the strings that make up the values...
@juanpa.arrivillaga, yep, thank you! I've already realized that. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.