python/pandas
21. pandas DataFrame - concat 함수. dataframe 병합
Abokadoh
2023. 2. 26. 20:34
concat()
함수를 사용해 DataFrame을 병합해보자.
concat()
은 두 dataframe을 열이나 행 레벨로 그대로 가져다 붙이는 아주 날 것의 병합 방법이다.
간단하게 실습으로 공부해보자.
실습을 위해 key와 value를 갖는 간단한 DataFrame을 만들어보았다.
import numpy as np
import pandas as pd
# <in>
df1 = pd.DataFrame({'key1' : np.arange(10), 'value1' : np.random.randn(10)})
df2 = pd.DataFrame({'key1' : np.arange(10), 'value1' : np.random.randn(10)})
print(df1)
print(df2)
이제 이 두 DataFrame을 concat
함수를 사용해 병합해보겠다.
1. concat() 함수 - [그대로 병합]
# <in>
pd.concat([df1, df2])
row level로 두 df가 병합된 것을 확인할 수 있다. 즉 concat()
함수의 axis parameter의 default값은 0이다.
# <in>
pd.concat([df1, df2], ignore_index = True)
ignore_index parmeter
의 값을 True로 부여하면 기존의 index를 무시하고 새로운 index를 만들어 병합한 데이터에 적용해준다.
axis parmeter에 1을 주면 어떻게 될까?
# <in>
pd.concat([df1, df2], axis = 1)
예상대로 column level로 df를 병합했다.
만약 row level로 병합할 때 column의 명이 다르면 어떻게 될까?
# <in>
df3 = pd.DataFrame({'key2' : np.arange(10), 'value2' : np.random.randn(10)})
실습을 위해 df1과 다른 column명을 가진 df를 생성했다.
# <in>
pd.concat([df1, df3], axis = 0)
날 것 그대로 정직하게 병합하고 부재인 값에 대해서는 NaN값을 반환한다