I have a pandas dataframe column with a list of names like so:
Names
Roger Williams, Anne Graham
Joe Smoe, Elliot Ezekiel
Todd Roger
And a dictionary with user_ids:
map = {Roger Williams: 1234, Anne Graham: 4892, Joe Smoe: 898, Elliot Ezekiel: 8458, Todd Roger: 856}
I need to use pandas .map function to map each name in the list with the user_id like so:
Names user_id
Roger Williams, Anne Graham 1234, 4892
Joe Smoe, Elliot Ezekiel 898, 8458
Todd Roger 856
Can someone help me accomplish this? I'm having a real hard time with it. Thanks!
In [124]: mapping
Out[124]:
{'Anne Graham': 4892,
'Elliot Ezekiel': 8458,
'Joe Smoe': 898,
'Roger Williams': 1234,
'Todd Roger': 856}
In [125]: df
Out[125]:
Names
0 Roger Williams, Anne Graham
1 Joe Smoe, Elliot Ezekiel
2 Todd Roger
In [126]: df.replace(mapping.keys(), list(map(str, mapping.values())), regex=True)
Out[126]:
Names
0 1234, 4892
1 898, 8458
2 856
if you have a list of strings:
In [131]: df
Out[131]:
Names
0 [Roger Williams, Anne Graham]
1 [Joe Smoe, Elliot Ezekiel]
2 [Todd Roger]
In [133]: df.Names.apply(', '.join).replace(mapping.keys(), list(map(str, mapping.values())), regex=True)
Out[133]:
0 1234, 4892
1 898, 8458
2 856
Name: Names, dtype: object
Leverage pd.Series
and astype(str)
df.replace(pd.Series(m).astype(str), regex=True)
Names
0 1234, 4892
1 898, 8458
2 856
Setup
df = pd.DataFrame({
'Names': [
'Roger Williams, Anne Graham',
'Joe Smoe, Elliot Ezekiel',
'Todd Roger'
]
})
m = {
'Roger Williams': 1234, 'Anne Graham': 4892,
'Joe Smoe': 898, 'Elliot Ezekiel': 8458, 'Todd Roger': 856
}
def get_values(g):
return ", ".join([map[x] for x in g])
df['Names'] = df['Names'].map(get_values)
0 1234, 4892
1 898, 8458
2 856
Name: Names, dtype: object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With