18_Merge

Merge

  • Merge Docs를 보면 데이터베이스의 Join 처럼 columns과 indexes을 사용하여 DataFrame을 Merge한다고 정의되어 있음
  • 기본 메소드 형태는 pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True,suffixes=('_x', '_y'), copy=True, indicator=False)
  • 중요 인자를 보면
    • left, right :Merge의 대상이 되는 DataFrame( Series면 DataFrame으로 변환해야 함)
    • how:기본은 'inner'로 되어 있고. left, right, outer를 선택할 수 있음
    • on :merge의 기준이 되는 key변수, left와 right에 동일 컬럼명 있을 경우 사용(Must be found in both DataFrames)
    • left_on, right_on: 왼쪽, 오른쪽 각각 merge의 기준이 되는 key변수. (label or list)
    • left_index, right_index:기본으로 False이며 True이면 Merege 키로 사
    • suffixes=('_x', '_y'):중복 컬럼시 접두어를 선택할 수 있음.
    • indicator = Merge된 DataFrame에 how에 따른 left_only, right_only, both의 출처를 표시.
In [1]:
import pandas as pd
import numpy as np

data = np.arange(12).reshape((-1, 4))
index = [2003,2004,2005]
columns = ['Arizona','Boston', 'Seoul','Detroit']
df_L= pd.DataFrame(data, index = index, columns = columns)
df_L
Out[1]:
ArizonaBostonSeoulDetroit
20030123
20044567
2005891011
In [2]:
data = np.arange(0, 12).reshape((-1, 4))
index = [2004,2005,2006]
columns = ['Pari','Roma', 'Seoul','Tokyo']
df_R= pd.DataFrame(data, index = index, columns = columns)
df_R
Out[2]:
PariRomaSeoulTokyo
20040123
20054567
2006891011
In [3]:
pd.merge(df_L, df_R, how= 'outer', left_on = 'Seoul', right_on ='Seoul' )
Out[3]:
ArizonaBostonSeoulDetroitPariRomaTokyo
00123013
14567457
28910118911
In [4]:
dfA = df_L.T.reset_index()
dfA = dfA.rename(columns={"index": "city"})
dfA
Out[4]:
city200320042005
0Arizona048
1Boston159
2Seoul2610
3Detroit3711
In [5]:
dfB = df_R.T.reset_index()
dfB = dfB.rename(columns={"index": "city"})
dfB
Out[5]:
city200420052006
0Pari048
1Roma159
2Seoul2610
3Tokyo3711
In [6]:
#inner merge
pd.merge(dfA, dfB, how = 'inner', left_on = 'city', right_on ='city' )
Out[6]:
city20032004_x2005_x2004_y2005_y2006
0Seoul26102610
In [7]:
#left merge
pd.merge(dfA, dfB, how = 'left', left_on = 'city', right_on ='city' )
Out[7]:
city20032004_x2005_x2004_y2005_y2006
0Arizona048NaNNaNNaN
1Boston159NaNNaNNaN
2Seoul26102.06.010.0
3Detroit3711NaNNaNNaN
In [8]:
#outer merge
pd.merge(dfA, dfB, how = 'outer', left_on = 'city', right_on ='city' )
Out[8]:
city20032004_x2005_x2004_y2005_y2006
0Arizona0.04.08.0NaNNaNNaN
1Boston1.05.09.0NaNNaNNaN
2Seoul2.06.010.02.06.010.0
3Detroit3.07.011.0NaNNaNNaN
4PariNaNNaNNaN0.04.08.0
5RomaNaNNaNNaN1.05.09.0
6TokyoNaNNaNNaN3.07.011.0


© 2017. All rights reserved.

Powered by ZooFighter v0.12