Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas replace value in column with key in dictionary

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading