I have a pandas dataframe I want to replace a certain column conditionally.
eg:
col
0 Mr
1 Miss
2 Mr
3 Mrs
4 Col.
I want to map them as
{'Mr': 0, 'Mrs': 1, 'Miss': 2}
If there are other titles now available in the dict then I want them to have a default value of 3
The above example becomes
col
0 0
1 2
2 0
3 1
4 3
Can I do this with pandas.replace() without using regex ?
To add on the answer by @jezrael: The most straight forward solution is to use a defaultdict instead of dict. This is especially useful when you want missing values not to be replaced with your default value.
The first argument of defaultdict is a function that return the default value.
You can use
map
rather asreplace
, because faster, thenfillna
by3
and cast toint
byastype
:Another solution with
numpy.where
and condition withisin
:Solution with
replace
:Timings: