logo

[pandas-basic] 데이터 합치기

판다스에서 여러 개의 데이터를 합치는 방법을 알아보겠습니다.

import pandas as pd
 

행방향 합치기

다음과 같은 표 df1이 있습니다.

df1 = pd.DataFrame({'A': [101, 102, 103],
                    'B': [201, 202, 203]},
                    index=[0, 1, 2])
df1
AB
0101201
1102202
2103203

df1의 아래에 다음의 df2와 같은 표를 이어붙이려고 합니다.

df2 = pd.DataFrame({'A': [105, 106, 107],
                    'B': [205, 206, 207]},
                   index=[3, 4, 5])
df2
AB
3105205
4106206
5107207

concat 함수를 이용하면 2개의 표을 이어 붙일 수 있습니다. 기본적으로 행 방향으로 이어붙입니다. 즉, 첫 번째 표의 아래에 두 번째 표를 붙입니다.

pd.concat([df1, df2])
AB
0101201
1102202
2103203
3105205
4106206
5107207

append 메소드를 이용해도 동일한 결과를 얻을 수 있습니다.

df1.append(df2)
AB
0101201
1102202
2103203
3105205
4106206
5107207
 

한 줄 추가

표에 한 행을 추가하는 방법은 조금 다릅니다. 다음과 같은 한 행이 있을 때,

s = pd.Series({'A': 104, 'B': 204})

df1에 바로 붙이면 오류가 발생합니다.

df1.append(s)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-cc786cf9da5a> in <module>
----> 1 df1.append(s)

~\Anaconda3\lib\site-packages\pandas\core\frame.py in append(self, other, ignore_index, verify_integrity, sort)
   7074             if other.name is None and not ignore_index:
   7075                 raise TypeError(
-> 7076                     "Can only append a Series if ignore_index=True"
   7077                     " or if the Series has a name"
   7078                 )

TypeError: Can only append a Series if ignore_index=True or if the Series has a name

이때는 ignore_index=True를 추가해줍니다.

df1.append(s, ignore_index=True)
AB
0101201
1102202
2103203
3104204
 

열방향 합치기

아래 표를 df1의 오른쪽에 붙여보겠습니다.

df3 = pd.DataFrame({'C': [301, 302, 303],
                    'D': [401, 402, 403]},
                    index=[0, 1, 2])
df3
CD
0301401
1302402
2303403

axis=1을 추가하면 열 방향으로 합칩니다.

pd.concat([df1, df3], axis=1)
ABCD
0101201301401
1102202302402
2103203303403
Previous
그룹핑