Python/Python Pandas
Python Pandas : concat (Series 합치기, DataFrame 합치기)
CosmosProject
2021. 1. 5. 18:30
728x90
반응형
Pandas의 concat은 두 개 이상의 Series를 합치거나, 두 개 이상의 DataFrame을 합쳐줍니다.
import pandas as pd
list_test_1 = [1, 2, 3]
list_test_2 = [4, 5, 6]
list_test_3 = [7, 8, 9]
seri_test_1 = pd.Series(list_test_1)
seri_test_2 = pd.Series(list_test_2)
seri_test_3 = pd.Series(list_test_3)
print(seri_test_1)
print(seri_test_2)
print(seri_test_3)
- Output
0 1
1 2
2 3
dtype: int64
0 4
1 5
2 6
dtype: int64
0 7
1 8
2 9
dtype: int64
먼저 테스트용 Series를 3개 생성합니다.
seri_concat = pd.concat([seri_test_1, seri_test_2, seri_test_3])
print(seri_concat)
- Output
0 1
1 2
2 3
0 4
1 5
2 6
0 7
1 8
2 9
dtype: int64
<class 'pandas.core.series.Series'>
위처럼 3개의 Series를 concat으로 합칠 수 있습니다.
또한 concat의 인자로서 합칠 Series들을 list에 담아 전달해야 합니다.
근데 위에서 한 가지 특징을 보면, concat을 적용한 Series의 index가 1, 2, 3, 4, 5, 6, 7, 8, 9가 아니라 0, 1, 2가 반복되고 있습니다.
이 말은 concat은 기본적으로 합칠 Series나 DataFrame의 index까지도 그대로 합쳐서 반환합니다.
seri_concat = pd.concat([seri_test_1, seri_test_2, seri_test_3], ignore_index=True)
print(seri_concat)
print(type(seri_concat))
- Output
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
dtype: int64
<class 'pandas.core.series.Series'>
만약 index를 reset하고싶으면 위처럼 ignore_index 값을 True로 설정해주면 됩니다.
import pandas as pd
dict_test_1 = {
'col1': [1, 2, 3],
'col2': ['a', 'b', 'c']
}
dict_test_2 = {
'col1': [4, 5, 6],
'col2': ['d', 'e', 'f']
}
dict_test_3 = {
'col1': [7, 8, 9],
'col2': ['g', 'h', 'i']
}
df_test_1 = pd.DataFrame(dict_test_1)
df_test_2 = pd.DataFrame(dict_test_2)
df_test_3 = pd.DataFrame(dict_test_3)
print(df_test_1)
print(df_test_2)
print(df_test_3)
- Output
col1 col2
0 1 a
1 2 b
2 3 c
col1 col2
0 4 d
1 5 e
2 6 f
col1 col2
0 7 g
1 8 h
2 9 i
DataFrame으로도 테스트를 해봅시다.
df_concat = pd.concat([df_test_1, df_test_2, df_test_3])
print(df_concat)
- Output
col1 col2
0 1 a
1 2 b
2 3 c
0 4 d
1 5 e
2 6 f
0 7 g
1 8 h
2 9 i
Series와 동일한 맥락으로 DataFrame들이 합쳐집니다.
df_concat = pd.concat([df_test_1, df_test_2, df_test_3], ignore_index=True)
print(df_concat)
- Output
col1 col2
0 1 a
1 2 b
2 3 c
3 4 d
4 5 e
5 6 f
6 7 g
7 8 h
8 9 i
마찬가지로 ignore_index option도 설정가능합니다.
728x90
반응형