취미와 밥줄사이

[Pandas] - DataFrame : merge 사용법과 코드 본문

Python/Pandas

[Pandas] - DataFrame : merge 사용법과 코드

취미와 밥줄사이 2021. 3. 21. 10:18

 

 

 

 

 

 

 

 

 

1. merge


  • Pandas에서 두 개의 데이터프레임의 결합하는 방식은 대표적으로 3가지가 있다. merge, join, concat 이렇게
  • 3개의 메소드가 존재한다. merge와 join, concat 상황에 따라 다르게 사용된다.
  • 오늘은 merge 메서드의 사용법에 대해서 알아보고자 한다. Pandas의 merge 메서드는 MySQL의 JOIN 키워드와 기능이 매우 유사하다. 기준열(공통속성)을 가진 열을 기준으로 데이터프레임을 병합하는 기능을 가진다.
  • merge 메서드의 how파라미터를 어떻게 사용하는지에 따라 결합방식이 달라지고 , on = 파라미터를 통해서 기준열을 설정할 수 있다.

2. 데이터프레임 생성


 

# 라이브러리 가져오기
import pandas as pd


# 데이터프레임 생성

book_titles =pd.DataFrame(data = {
   'book_id':[1, 2, 3, 4, 5],
    'title': ['별헤는 밤', '자유론','복학왕', '자료구조', '텐서플로우']
})


book_reviews =pd.DataFrame(data = {
    'book_id':[1, 2, 3, 4, 5],
    'review': ['재미', '슬픔','기쁨', '행복', '절망']
})

(1)
(2)

2. how : 결합방식 설정


2-1. how: left


  • left로 설정한 데이터프레임을 기준으로 병합
 pd.merge(book_title, book_review, how='left')

2-2. how: right


  • right로 설정한 데이터프레임을 기준으로 병합
pd.merge(book_title, book_review, how='right')

2-3. how: inner


  • 교집합
pd.merge(book_title, book_review, how='inner')

2-4. how: outer


  • 모든 index가 누락되지 않고 데이터프레임으로 형성
pd.merge(book_title, book_review, how='outer')

 

Reference


pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html?highlight=merge#pandas.DataFrame.merge

 

pandas.DataFrame.merge — pandas 1.2.4 documentation

If True, adds a column to the output DataFrame called “_merge” with information on the source of each row. The column can be given a different name by providing a string argument. The column will have a Categorical type with the value of “left_only

pandas.pydata.org

(https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html?highlight=merge#pandas.DataFrame.merge)

 

pandas.DataFrame.merge — pandas 1.2.4 documentation

If True, adds a column to the output DataFrame called “_merge” with information on the source of each row. The column can be given a different name by providing a string argument. The column will have a Categorical type with the value of “left_only

pandas.pydata.org

 

https://pandas.pydata.org/about/citing.html

 

pandas - Python Data Analysis Library

Citing and logo Citing pandas If you use pandas for a scientific publication, we would appreciate citations to the published software and the following paper: pandas on Zenodo, Please find us on Zenodo and replace with the citation for the version you are

pandas.pydata.org