Pandas replace value in column with key in dictionary

Advertisements

I’m trying to replace each value of a column in my pandas df with dict key if the value == the value of the dictionary:

Example dic: {'The Name of the Rose': '9780544176560'}

Example df:

ISBN, link
9780544176560, https://link

Code:

df['ISBN'] = df['ISBN'].astype(str)
for k,v in dic.items():
    for x in df['ISBN']:
        x = str(x)
        if x == v:
            print(True)
            x = k

It prints True every time, and if I print x I get the correct titles, but then when I print the df it returns numbers like nothing changed. I also tried replace but nothing changed

>Solution :

You should use map, but you’re building your dictionary the wrong way.

As ISBN are unique, they can be used as key. A book title could not be unique though:

dic = {'The Name of the Rose': '9780544176560'}
df = pd.DataFrame({'ISBN': [9780544176560],
                   'link': ['https://link']})

# invert the dictionary if needed
# but the best it to build it directly with ISBN as key
dic = {isbn:title for title,isbn in dic.items()}
# {'9780544176560': 'The Name of the Rose'}

# map the Title from the ISBN
df['Title'] = df['ISBN'].astype(str).map(dic)

output:

            ISBN          link                 Title
0  9780544176560  https://link  The Name of the Rose

Leave a ReplyCancel reply