0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonでSQL使ってみた エピソードⅡ : データの横結合 left join inner join

Last updated at Posted at 2020-07-21

SQLを用いたデータのハンドリング
pythonでSQLを使うシリーズ2

※以下はgroup byの紹介
https://qiita.com/saspy/items/2b5aeef91e87cac503e2

SAS/Rのデータの結合比較
https://qiita.com/saspy/items/43b4c368d22f45f023a2

今回はleft joinなどデータの結合を紹介

準備

import pandas as pd
import dask.dataframe as dd
from pandasql import sqldf
import sqlite3

Data1 <- dd.read_csv( "パス/ファイル名" )
Data2 <- dd.read_csv( "パス/ファイル名" )

Data1とData2を横結合する

pandasql sqldf

query = """
  select A.変数1 , A.変数2 , B.変数1 , ...
  from Data1 as A
  left join Data2 as B
  結合条件on A.キー変数1 = B.キー変数1 and A.キー変数2 = B.キー変数2 ...
  order by A.変数1 , A.変数2 , ...;
"""
Data = sqldf( query , locals() )

left joinをinner joinに変えれば、左結合から内部結合へ修正可能
right joinやfull joinにするとエラーが出た
Rのsqldfと同様、left joinとinner joinだけなのかも...

SQLite3 read_sql_query

conn = sqlite3.connect( "" )
# db残したいor既存のを使用するなら"パス/db名.db"と指定

# data.frameをSQL化(dbにすでに格納されているなら不要)
Data1.to_sql( "Data1_Sql" , conn )
Data2.to_sql( "Data2_Sql" , conn )

query = """
  select A.変数1 , A.変数2 , B.変数1 , ...
  from Data1_Sql as A
  left join Data2_Sql as B
  結合条件on A.キー変数1 = B.キー変数1 and A.キー変数2 = B.キー変数2 ...
  order by A.変数1 , A.変数2 , ...
"""
# ;なし
Data = pd.read_sql_query( sql = query , con = conn )

conn.close()

left joinをinner joinに変えれば、左結合から内部結合へ修正可能
また、こっちでもright joinやfull joinを使うと以下のエラーが出た
RIGHT and FULL OUTER JOINs are not currently supported

まぁrightは使わない気もするが
Rのsqldfやpythonのsqldf、read_sql_queryではfull joinは使えないようだ
ダミーデータ作ってleft joinするか、別のパッケージ使うしかないかな

daskやpandasによるmerge

DATA = dd.merge( Data1 , Data2 , on = [ "キー変数1" , "キー変数2" , ... ] , how = "left" )

# pandasならddをpdにする

こちらもhow = "left"をrightやinner,outerへ変更可能

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?