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 merge 2 columns from dict

I’ve got two dictionaries:

game_data = {
    'game_id': range(1, 6),                
    'title': ('LOL', 'WH40K',
              'WOW', 'POE',
              'KEK'),                      
    'author_id': (1, 1, 2, 3, 5),           
    'genre_id': (1, 2, 4, 4, 1),           
    'price': (0, 0, 14, 19, 100)           
}

author_data = {
    'author_id': (1, 2, 3, 4),     
    'author_name': ('Graham McNeill',
                    'Christie Golden',
                    'Nick Jones',
                    'Slaik')       
}

The task is to create the dataframe using dictionaries above in this way:
new dataframe should contain only two columns: title & author_name:

   title      author_name
0    LOL   Graham McNeill
1  WH40K   Graham McNeill
2    WOW  Christie Golden
3    POE       Nick Jones

I’ve tried

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

print(pd.merge(
    df1, df2,
    left_on='title',
    right_on='author_name',
    how='inner'
))

but it doesn’t work

>Solution :

A possible solution (you should replace left_on='title', right_on='author_name' by on='title'):

df1 = pd.DataFrame.from_dict(game_data)
df2 = pd.DataFrame.from_dict(author_data)

df1.merge(df2, on='author_id', how='inner')[['title', 'author_name']]

Output:

   title      author_name
0    LOL   Graham McNeill
1  WH40K   Graham McNeill
2    WOW  Christie Golden
3    POE       Nick Jones
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