AI 그게 뭔데
끄적끄적 개발일지
AI 그게 뭔데
전체 방문자
오늘
어제
  • 분류 전체보기 (342)
    • 논문 (5)
    • DL(Deep-Learning) (34)
      • 개념 (14)
      • Python 기초 (14)
      • Tensorflow (6)
      • Pytorch (0)
    • NLP (10)
    • OpenCV (53)
    • DevOps (10)
      • AWS (2)
      • Docker & Kubernetes (4)
      • Spark (3)
      • SQL (1)
    • MacOS (1)
    • React-Native (2)
    • BI (3)
      • GA(Google Analytics) (3)
      • Tableau (0)
    • 알고리즘 (221)
      • 백준 (76)
      • 프로그래머스 (108)
      • 기타 알고리즘 (37)

인기 글

태그

  • OpenCV
  • 백준
  • 프로그래머스
  • Python
  • level1
  • LEVEL2
  • 이코테
  • 파이썬
  • 알고리즘
  • 연습문제

최근 글

hELLO · Designed By 정상우.
AI 그게 뭔데

끄적끄적 개발일지

DL(Deep-Learning)/Python 기초

DataFrame 합치기1 (concat, merge, join)

2022. 1. 26. 22:15

데이터 프레임 붙이기 : pd.concat()

pd.concat()함수는 데이터프레임을 말 그대로 물리적으로 이어 붙여주는 함수이다.

 

두 가지의 데이터 프레임을 만들어보자.

 

import pandas as pd

df1 = pd.DataFrame({'a':['a0','a1','a2','a3'],
                   'b':['b0','b1','b2','b3'],
                   'c':['c0','c1','c2','c3']},
                  index = [0,1,2,3])

df2 = pd.DataFrame({'a':['a2','a3','a4','a5'],
                   'b':['b2','b3','b4','b5'],
                   'c':['c2','c3','c4','c5'],
                   'd':['d2','d3','d4','d5']},
                   index = [2,3,4,5])

print(df1,'\n\n', df2)
더보기
  a b c
0 a0  b0 c0
1 a1  b1  c1 
2 a2  b2  c2 
3 a3  b3  c3

 

  a b c d
2 a2 b2 c2 d2
3 a3 b3 c3 d3
4 a4 b4 c4 d4
5 a5 b5 c5 d5

 

 

위의 두 데이터프레임을 살펴보면 행 index명과 컬럼명이 다르다.

pd.concat() 함수를 사용하면 어떻게 결과가 나타날지 확인해보자.

 

 

1. 기본 concat

result = pd.concat([df1, df2]) # axis=0 default
print(result)
더보기
  a b c d
0 a0 b0 c0 NaN
1 a1 b1 c1 NaN
2 a2 b2 c2 NaN
3 a3 b3 c3 NaN
2 a2 b2 c2 d2
3 a3 b3 c3 d3
4 a4 b4 c4 d4
5 a5 b5 c5 d5

 

pd.concat() 에 들어가는 인자 값으로는 리스트를 받는다는 특징이 있다.

 

axis=0이 적용되기 때문에 행방향(위아래)으로 데이터 프레임을 이어 붙인다.그리고 df1에는 d열이 없으므로 NaN값이 채워진 것을 알 수 있다.

 

 

2. 인덱스 재배열 ignore_index = True 

이 때 행 인덱스를 재배열하기 위한 옵션으로 ignore_index=True를 지정할 수 있다.

 

result = pd.concat([df1,df2], ignore_index=True)
print(result)
더보기
  a b c d
0 a0 b0 c0 NaN
1 a1 b1 c1 NaN
2 a2 b2 c2 NaN
3 a3 b3 c3 NaN
4 a2 b2 c2 d2
5 a3 b3 c3 d3
6 a4 b4 c4 d4
7 a5 b5 c5 d5

 

2.1 null값 채우기 fillna()

result.fillna(0)
더보기
  a b c d
0 a0 b0 c0 0
1 a1 b1 c1 0
2 a2 b2 c2 0
3 a3 b3 c3 0
4 a2 b2 c2 d2
5 a3 b3 c3 d3
6 a4 b4 c4 d4
7 a5 b5 c5 d5

 

3. 열 방향 병합 axis = 1

axis=1 값을 주면 열 방향으로 병합을 할 수 있다.

 

result = pd.concat([df1,df2],axis=1)
print(result)
더보기
  a b c a b c d
0 a0 b0 c0 NaN NaN NaN NaN
1 a1 b1 c1 NaN NaN NaN NaN
2 a2 b2 c2 a2 b2 c2 d2
3 a3 b3 c3 a3 b3 c3 d3
4 NaN NaN NaN a4 b4 c4 d4
5 NaN NaN NaN a5 b5 c5 d5

 

 

4. 병합방식 변경 join = 'inner'

pd.concat() 함수는 또한 default로 outer를 가진다. outer는 합집합, inner는 교집합을 의미한다.

두 데이터가 모두 갖고 있는 행 인덱스를 가져오기 위해 join = 'inner' option을 적용해 보자.

 

result = pd.concat([df1,df2],axis=1, join='inner')   #열방향(axis=1), 교집합(inner)
print(result)
더보기
  a b c a b c d
2 a2 b2 c2 a2 b2 c2 d2
3 a3 b3 c3 a3 b3 c3 d3

 

 

5. 그 외의 옵션

 Pandas 공식문서를 통해 다양한 옵션을 확인할 수 있다.

 

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

 

pandas.concat — pandas 1.4.0 documentation

If True, do not use the index values along the concatenation axis. The resulting axis will be labeled 0, …, n - 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index

pandas.pydata.org

 

 


Series 데이터와 DataFrame의 병합 - pd.concat

Sereis는 하나의 컬럼이라고 이해하고 병합을 해주면 된다.

시리즈 객체를 생성할때 주는 옵션 name이, 시리즈가 데이터프레임에 결합되었을 떄의 열이름이 된다.

 

sr1 = pd.Series(['e0','e1','e2','e3'], name = 'e')
sr2 = pd.Series(['f0','f1','f2'], name = 'f', index = [3,4,5])
result1 = pd.concat([df1, sr1], axis=1)
print(result1, '\n')

result2 = pd.concat([df2, sr2], axis=1)
print(result2, '\n')
더보기
  a b c e
0 a0  b0 c0 e0
1 a1  b1  c1  e1
2 a2  b2  c2  e2
3 a3  b3  c3 e3

 

  a b c d f
2 a2 b2 c2 d2 NaN
3 a3 b3 c3 d3 f0
4 a4 b4 c4 d4 f1
5 a5 b5 c5 d5 f2

 

 

sr1의 name은 e로 e열이 데이터 프레임에 붙여졌음을 볼 수 있다.

sr2의 name은 f, index는 3,4,5로 지정해줬으므로, 해당 행인덱스에 맞춰 열 f로 이어붙여졌음을 볼 수 있다.

 

 

Series간의 병합 - pd.concat

sr1 = pd.Series(['e0','e1','e2','e3'], name = 'e')
sr2 = pd.Series(['f0','f1','f2'], name = 'f', index = [3,4,5])
sr3 = pd.Series(['g0','g1','g2','g3'], name = 'g')
result1 = pd.concat([sr1, sr3], axis = 1)  #열방향 연결, 데이터프레임
print(result1)
print(type(result1), '\n')

result2 = pd.concat([sr1, sr3], axis = 0)  #행방향 연결, 시리즈
print(result2)
print(type(result2), '\n')
더보기
    e     g
0  e0  g0
1  e1  g1
2  e2  g2
3  e3  g3
<class 'pandas.core.frame.DataFrame'> 

0    e0
1    e1
2    e2
3    e3
0    g0
1    g1
2    g2
3    g3
dtype: object
<class 'pandas.core.series.Series'>

 

sr1과 sr3가 index를 지정하지 않았기 때문에 인덱스 0,1,2,3으로 열방향으로 병합이 되었다.

또한 행방향으로 연결을 했을 때, 인덱스가 0,1,2,3이 반복적으로 생성이 되고 데이터 타입 또한 시리즈로 반환되는 것을 볼 수 있다.

'DL(Deep-Learning) > Python 기초' 카테고리의 다른 글

[Python] 파일 이름 변경하기  (0) 2022.01.26
DataFrame 합치기2 (concat, merge, join)  (0) 2022.01.26
[Python] Raw String이란?  (0) 2022.01.26
[Python] 파일과 디렉토리 경로 설정하기  (0) 2022.01.26
[Python] 예외처리  (0) 2022.01.26
    AI 그게 뭔데
    AI 그게 뭔데
    공부와 개발 그리고 AI가 약간 첨가된 흔적 남기기

    티스토리툴바