pandas concat / join / merge

Published by onesixx on

import pandas as pd
import plotly.express as px
iris = px.data.iris()

iris_setosa     = iris[ iris.species == 'setosa']
iris_versicolor = iris[iris.species.isin(['versicolor'])]
iris_virginica  = iris.query("species=='virginica'")

iris_length = iris.filter(like="_length")
iris_width  = iris.filter(like="_width")

행 +  행

result1 = pd.concat([iris_versicolor, iris_setosa], ignore_index=True)
result2 = iris_versicolor.append(iris_setosa, ignore_index=True)

열 + 열

result3 = pd.concat([iris_length,iris_width ], axis=1, ignore_index=True)

pd.concat(objs, [, key=리스트], axis=0, join='outer')

  • objs : 합칠 DataFrame을 리스트로 전달.
  • keys=[]를 이용해 합친 행들을 구분하기 위한 다중 인덱스 처리.
  • axis
    • 0 또는 index : 수직 결합
    • 1 또는 columns : 수평 결합
  • join : 조인방식
    • ‘outer'(기본값)
    • ‘inner’
import numpy as np
import pandas as pd

left = pd.DataFrame({
    'Sr.no': ['1', '2', '3', '4', '5'],
    'Name': ['Rashmi', 'Arun', 'John', 'Kshitu', 'Bresha'],
    'Roll No': ['1', '2', '3', '4', '5']
})
 
right = pd.DataFrame({
    'Sr.no': ['2', '4', '6', '7', '8'],
    'Gender': ['F', 'M', 'M', 'F', 'F'],
    'Interest': ['Writing', 'Cricket', 'Dancing', 'Chess', 'Sleeping']
})

pd.merge(left, right, how ='inner', on ='Sr.no')
#   Sr.no\tName   \tRoll No\tGender\tInterest
# 0\t    2\tArun\t2\t    F\t    Writing
# 1\t    4\tKshitu\t4\t    M\t    Cricket

DataFrame객체.join(oters, how='left', lsuffix='', rsuffix='')

  • lsuffix, rsuffix
    • 조인 대상 Dataframe에 같은 이름의 컬럼이 있으면 에러 발생.
    • 같은 이름이 있는 경우, 붙일 접미어를 지정해준다.
  • how : 조인 방식.
    • ‘left’ : 기본값
    • ‘right’
    • ‘outer’
    • ‘inner

DataFrame.merge(합칠dataframe, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False)

  • on
    • 같은 컬럼명이 여러 개일 때, join 대상 컬럼을 선택
    • 여러 개 중 골라서 할 수 있다.
  • left_on, right_on
    • 조인할 때 사용할 왼쪽, 오른쪽 DataFrame의 컬럼 이름
  • left_index, right_index
    • 조인할 때 index를 사용할 경우, True로 지정
  • how : 조인 방식
    • ‘left’
    • ‘right’
    • ‘outer’
    • ‘inner’ : 기본값
  • suffixes
    • 두 dataframe에 같은 이름의 컬럼 이름이 있을 경우, 구분을 위해서 붙인 접미어를 리스트로 설정.
    • 생략할 시, x와 y를 붙인다. ex _x, _y
Categories: pandas

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x