Replace values ​​in pandas Series with dictionary

I want to replace values ​​in pandas Serieswith a dictionary. I follow the @DSM accepted answer with this:

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

But this does not affect:

0    abc
1    abe
2    abg
dtype: object

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

+4
source share
1 answer

You can do this using the parameter regex=True:

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

As you already learned , this is a replacement for RegEx, and it won’t work as you expected:

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

works as expected:

In [38]: s.replace({'abc':'ABC'})
Out[38]:
0    ABC
1    abe
2    abg
dtype: object
+4

Source: https://habr.com/ru/post/1657930/


All Articles