Reputation: 1449
I have a Pandas column with string value entries, which I have ensured are strings via
df[col].astype(str)
And I have created a dictionary out of an enumeration of these string values that takes the form
{...'hello': 56, 'yello': 71,...}
I have tried multiple map/replace implementations, but I cannot get the string values to update with their dictionary integer.
df[col].replace(lambda s: inv_map.get(s) if s in inv_map else s)
Is the most recent one I have tried. I dont get any errors or warnings, it simply doesnt map the values.
Upvotes: 1
Views: 468
Reputation: 30605
I think you are looking for apply
i.e
df = pd.DataFrame({"a":['hello','yello','bye','seeya']})
inv_map = {'hello': 56, 'yello': 71}
col = 'a'
df[col]=df[col].apply(lambda s: inv_map.get(s) if s in inv_map else s)
0 56 1 71 2 bye 3 seeya Name: a, dtype: object
Hope this helps.
Upvotes: 2
Reputation: 1272
df = pd.DataFrame(['hello', 'yellow'], columns=['col_name'])
inv_map = {'hello': 56, 'yellow': 71}
df.replace(dict(col_name=inv_map))
col_name
0 56
1 71
# or just use
df['col_name'].replace(inv_map)
0 56
1 71
Name: col_name, dtype: int64
Upvotes: 0
Reputation: 7038
You can replace values in a column by the values in a dictionary using map()
:
# sample data
df
a
0 asd
1 er
2 sdf
3 qwe
dic = {'asd': 21, 'er':90}
df['dic_value'] = df.a.map(dic)
df
a dic_value
0 asd 21.0
1 er 90.0
2 sdf NaN
3 qwe NaN
Upvotes: 1