1

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.

redress
  • 1,399
  • 4
  • 20
  • 34

3 Answers3

2

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.

Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108
1

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
Andrew L
  • 6,618
  • 3
  • 26
  • 30
0
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
heyu91
  • 1,174
  • 11
  • 18
  • 1
    **From review queue:** May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. See also [Explaining entirely code-based answers](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers). – help-info.de Jul 27 '17 at 18:13