여러 pandas dataframe을 스택하는 방법


종종 두 개 이상의 Pandas DataFrame을 쌓고 싶을 수도 있습니다. 다행히도 pandas concat() 함수를 사용하면 이 작업을 쉽게 수행할 수 있습니다.

이 튜토리얼에서는 이를 수행하는 방법에 대한 몇 가지 예를 보여줍니다.

예 1: Pandas DataFrame 두 개 쌓기

다음 코드는 두 개의 Panda DataFrame을 서로 “스택”하고 DataFrame을 생성하는 방법을 보여줍니다.

 import pandas as pd

#create two DataFrames
df1 = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E'],
                    'points':[12, 5, 13, 17, 27]})

df2 = pd.DataFrame({'player': ['F', 'G', 'H', 'I', 'J'],
                    'points':[24, 26, 27, 27, 12]})

#"stack" the two DataFrames together
df3 = pd. concat ([df1,df2], ignore_index= True )

#view resulting DataFrame
df3

	player points
0 to 12
1 B 5
2 C 13
3 D 17
4 E 27
5 F 24
6 G 26
7:27 a.m.
8 I 27
9 D 12

예 2: Pandas DataFrame 3개 쌓기

유사한 코드를 사용하여 세 개의 팬더 DataFrame을 서로 쌓아서 DataFrame을 만들 수 있습니다.

 import pandas as pd

#create three DataFrames
df1 = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E'],
                    'points':[12, 5, 13, 17, 27]})

df2 = pd.DataFrame({'player': ['F', 'G', 'H', 'I', 'J'],
                    'points':[24, 26, 27, 27, 12]})

df3 = pd.DataFrame({'player': ['K', 'L', 'M', 'N', 'O'],
                    'points':[9, 5, 5, 13, 17]})

#"stack" the two DataFrames together
df4 = pd. concat ([df1,df2, df3], ignore_index= True )

#view resulting DataFrame
df4

        player points
0 to 12
1 B 5
2 C 13
3 D 17
4 E 27
5 F 24
6 G 26
7:27 a.m.
8 I 27
9 D 12
10K 9
11 L 5
12 M 5
13 N 13
14 O 17

ignore_index의 중요성

이전 예에서는 ignore_index=True를 사용했습니다.

이는 팬더에게 각 DataFrame의 인덱스 번호를 무시하고 새 DataFrame에 대해 0에서 n-1 범위의 새 인덱스를 생성하도록 지시합니다.

예를 들어, 다음 두 DataFrame을 스택할 때 ignore_index=True를 사용하지 않으면 어떤 일이 발생하는지 생각해 보세요.

 import pandas as pd

#create two DataFrames with indices
df1 = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E'],
                    'points':[12, 5, 13, 17, 27]},
                    index=[0, 1, 2, 3, 4])

df2 = pd.DataFrame({'player': ['F', 'G', 'H', 'I', 'J'],
                    'points':[24, 26, 27, 27, 12]},
                    index=[2, 4, 5, 6, 9])

#stack the two DataFrames together
df3 = pd. concat ([df1,df2])

#view resulting DataFrame
df3

        player points
0 to 12
1 B 5
2 C 13
3 D 17
4 E 27
2 F 24
4G 26
5:27 a.m.
6 I 27
9 D 12

결과 DataFrame은 두 DataFrame의 원래 인덱스 값을 유지했습니다.

따라서 원래 인덱스 값을 유지해야 하는 특별한 이유가 없는 한 두 개의 DataFrame을 쌓을 때 일반적으로 ignore_index=True를 사용해야 합니다.

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas DataFrame에 빈 열을 추가하는 방법
Pandas DataFrame에 열을 삽입하는 방법
Pandas DataFrame을 Excel로 내보내는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다