redress
redress

Reputation: 1449

Cannot Replace Pandas Column With Dictionary

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

Answers (3)

Bharath M Shetty
Bharath M Shetty

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

heyu91
heyu91

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

Andrew L
Andrew L

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

Related Questions