Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in pandas Series with dictionary

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.

like image 292
joga Avatar asked Oct 16 '16 20:10

joga


People also ask

How do I change the values in pandas series based on conditions?

You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.

How do I change my series on pandas?

Change data type of a series in PandasUse a numpy. dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy. dtype or Python type to cast one or more of the DataFrame's columns to column-specific types.

How do you replace elements in pandas?

replace() function is used to replace a string, regex, list, dictionary, series, number, etc. from a Pandas Dataframe in Python. Every instance of the provided value is replaced after a thorough search of the full DataFrame.


1 Answers

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
like image 83
MaxU - stop WAR against UA Avatar answered Sep 28 '22 02:09

MaxU - stop WAR against UA