Trying to figure out the best way to iterate a series through a dictionary in pandas. Here is my MRE:
s1 = pd.Series(['a','b','c','d'])
d = {'a':1, 'b':2, 'c':3, 'd':4}
what I want to do is create s2 such that
s2 = pd.Series([1,2,3,4])
by processing s1 through d. So far, the best way I can think of is
s2 = pd.Series([d[item] for item in list(s1)])
I am aware of the option to do
s2 = pd.Series(d.values())
but the actual problem I am trying to solve would require passing the series through a dictionary.
CodePudding user response:
You can use map
:
s1 = pd.Series(['a','b','c','d'])
d = {'a':1, 'b':2, 'c':3, 'd':4}
s2 = s1.map(d)
output:
0 1
1 2
2 3
3 4
CodePudding user response:
Try with replace
s2 = s1.replace(d)
s2
Out[17]:
0 1
1 2
2 3
3 4
dtype: int64