Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Dendi Handian
Dendi Handian

Posted on • Edited on

     

SQL Query into Pandas DataFrame - Part 3

After playing some aggregation and grouping in thelast part, now we will play harder with table joins.

The Playground Database

We will be using the same SQLite database, but now we are going to use some tables. So get all the required csv fileshere

Preparing the DataFrame

importpandasaspdalbums_df=pd.read_csv("albums.csv")artists_df=pd.read_csv("artists.csv")
Enter fullscreen modeExit fullscreen mode

Join Queries into Pandas DataFrame

INNER JOIN:

SQL:

SELECT*FROMalbumsJOINartistsONalbums.ArtistId=artists.ArtistId
Enter fullscreen modeExit fullscreen mode

or

SELECT*FROMalbumsINNERJOINartistsONalbums.ArtistId=artists.ArtistId
Enter fullscreen modeExit fullscreen mode

Pandas:

# For the exact same column name on both tablealbums_df.merge(artists_df,on='ArtistId')# Defining the join column of each tablesalbums_df.merge(artists_df,left_on='ArtistId',right_on='ArtistId')# To make sure we use the INNER onealbums_df.merge(artists_df,left_on='ArtistId',right_on='ArtistId',how='inner')
Enter fullscreen modeExit fullscreen mode

LEFT JOIN

SQL:

SELECT*FROMalbumsLEFTJOINartistsONalbums.ArtistId=artists.ArtistId
Enter fullscreen modeExit fullscreen mode

Pandas:

albums_df.merge(artists_df,on='ArtistId',how='left')
Enter fullscreen modeExit fullscreen mode

RIGHT JOIN

SQL:

SELECT*FROMalbumsRIGHTJOINartistsONalbums.ArtistId=artists.ArtistId
Enter fullscreen modeExit fullscreen mode

Pandas:

albums_df.merge(artists_df,on='ArtistId',how='right')
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Data Engineer - Building Data Lake & Modern Data Architecture
  • Location
    Jakarta
  • Education
    B.S. Computer Science
  • Work
    Data Engineer at Media Production Company
  • Joined

More fromDendi Handian

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp