말랑말랑제리스타일

[Pandas] DataFrame 합치기 - Union all 기능 본문

프로그래밍/파이썬

[Pandas] DataFrame 합치기 - Union all 기능

제리제리 2022. 1. 23. 07:59

RDBMS를 다뤄봤다면 누구나 알고있을 Union all 집합연산과 Join 기능이 판다스의 DataFrame에도 있습니다.

이번 장에서는 먼저 Union All 기능과 동일한 pandas.concat() 함수로 두개의 DataFrame을 합쳐보겠습니다.

 

test_df = pd.read_csv("/content/test.csv")
test_df_p1 = test_df.loc[test_df.Pclass == 1]
test_df_p2 = test_df.loc[test_df.Pclass == 2]
test_df_p3 = test_df.loc[test_df.Pclass == 3] # 0.DataFrame 생성

test_df_p12 = pd.concat([test_df_p1,test_df_p2]) # 1.p1과 p2 Union All

test_df_p2 = test_df_p2.rename(columns= {'Name':'Pname'})
test_df_p12 = pd.concat([test_df_p1,test_df_p2]) # 2.p2의 컬럼명 바꾼 후 Union All

0. DataFrame 생성

DataFrame에 테스트 데이터를 갖고온 뒤 Pclass에 따라 3개의 테이블을 생성해줍니다.

1. concat 함수 호출

pd.concate([DataFrame1,DataFrame2,...])을 이용해 DataFrame 목록을 리스트 형태로 전달해주고 속한 DataFrame으로 Union All 즉 데이터를 전부 넣어주는 연산을 수행합니다.

2. 컬럼 명이 다른 경우

DataFrame1과 DataFrame2의 컬럼 명칭이 다른 경우 SQL처럼 에러가 나지는 않지만 아래 그림과 같이 원치 않는 결과를 얻을 수 있습니다.

반응형
Comments