Home > OS >  Pandas replace values with dictionary values using python built in map() function
Pandas replace values with dictionary values using python built in map() function

Time:09-25

I have a dictionary like this {'Note1':'Desc1','Note2':'Desc2','Note3':'Desc3'} and a dataframe with values like this:

{0: 'Note1',
 1: 'Note1',
 2: 'Note1',
 3: 'Note2',
 4: 'Note2',
 5: 'Note2;Note3',
 6: 'Note2;Note3',
 7: 'Note3',

I want to have a new column where the description is mapped to the note number, so I do this:

df['noteText'] = df['NoteRef'].map(notelist)

This works great, except that the double values return NaN. So I made this:

def swap(x):
    x = x.split(';')
    for y in x:
        y = map(notelist, y)

swap(df['NoteRef'].iloc[-2]) # just to test
df['noteText'] = df['NoteRef'].apply(swap)

But I don't really know how map() in python would work here (doesn't work like in pandas). When I print y I get a map object, when I print list(y) I get TypeError: 'dict' object is not callable.

So I'm hoping someone can point me in the right direction, as this seems like something easy. If there is a better way to do this, I would greatly appreciate learning it. Thank you.

CodePudding user response:

Figured it out thanks to this post.

def swap(x):
    x = x.split(';')
    x = [*map(notelist.get, x)]
    x = ",".join(x)
    return x
df['noteText'] = df['NoteRef'].apply(swap)
  • Related