본문 바로가기

IT/Python

Pandas DataFrame 연결하기 ( Union )

 

다음과 같은 2개의 데이터 셋이 있다고 가정할 떄,

Rows 방향으로 붙이는 방법에 대해 알아 보도록 하겠습니다.

sample_dataset1

   a  b 
0  1  3 
1  2  4

 

sample_dataset2

  b  d 
0  1  3 
1  2  4

 

이때, 원하는 결과는 없는 컬럼은 자동으로 생성해주는 데이터 셋입니다. 

 

result_dataset

     a  b    d 
0  1.0  3  NaN 
1  2.0  4  NaN 
0  NaN  1  3.0 
1  NaN  2  4.0

 

Pandas concat을 이용해서 연결하기 

import pandas as pd

sample_dict1 = {'a': [1, 2], 'b': [3, 4]}
sdf_1 = pd.DataFrame(sample_dict1)
print(sdf_1)

sample_dict2 = {'b': [1, 2], 'd': [3, 4]}
sdf_2 = pd.DataFrame(sample_dict2)
print(sdf_2)

union_df = pd.concat([sdf_1, sdf_2], sort=True)
print(union_df)

 

Concat 이라는 함수를 이용해서 쉽게 사용할 수 있습니다. 

 

 

 

반응형