.merge를 사용하면 된다

how를 이용하여 inner, left, right, outer, cross를 정할 수 있으며, on에 key값을 입력하면 된다.

df_new = pd.merge(df_A, df_B, on='key_column', how='inner')
df_new = pd.merge(df_A, df_B, on='key_column', how='left')
df_new = pd.merge(df_A, df_B, on='key_column', how='right')
df_new = pd.merge(df_A, df_B, on='key_column', how='outer')
df_new = pd.merge(df_A, df_B, on='key_column', how='cross')

1. Inner Join : 교집합, A ∩ B

https://stackoverflow.com/questions/53645882/pandas-merging-101

2. Left Join : A ∪ (B - A)

https://stackoverflow.com/questions/53645882/pandas-merging-101

3. Right Join : B ∪ (A - B)

https://stackoverflow.com/questions/53645882/pandas-merging-101

4. Outer Join : 합집합, A∪B, Full Outer Join 이라고도 부른다.

https://stackoverflow.com/questions/53645882/pandas-merging-101

5. Cross Join : 곱집합, A×B

https://en.wikipedia.org/wiki/Cartesian_product

그 외에도 Excluding 하는 Join이 있다.

6. Left-Excluding Join: A - B

https://stackoverflow.com/questions/53645882/pandas-merging-101

df_new = df_A.merge(df_B, on='key_column', how='left', indicator=True)\
				.query('_merge == "left_only"')\
				.drop('_merge', 1)

7. Right-Excluding Join: B - A

https://stackoverflow.com/questions/53645882/pandas-merging-101

df_new = df_A.merge(df_B, on='key_column', how='left', indicator=True)\
				.query('_merge == "right_only"')\
				.drop('_merge', 1)

8. Outer-Excluding Join: ANTI Join, A - ( A ∩ B)

https://stackoverflow.com/questions/53645882/pandas-merging-101

df_new = df_A.merge(df_B, on='key_column', how='outer', indicator=True)\
				.query('_merge != "both"')\
				.drop('_merge', 1)

'자주찾는 Python Code' 카테고리의 다른 글

파이썬 데이터 열 (Column) / 행 (Row) 삭제  (0) 2023.03.06

+ Recent posts