여러 pandas dataframe을 추가하는 방법(예제 포함)


다음 기본 구문을 사용하여 여러 Pandas DataFrame을 한 번에 추가할 수 있습니다.

 import pandas as pd

#append multiple DataFrames
df_big = pd. concat ([df1,df2, df3], ignore_index= True ) 

이 특정 구문은 df1 , df2df3 을 df_big 이라는 단일 팬더 DataFrame에 추가합니다.

다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.

예 1: 여러 Pandas DataFrame을 한 번에 추가

다음 코드는 여러 Pandas 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]})

#append all DataFrames into one DataFrame
df_big = pd. concat ([df1,df2, df3], ignore_index= True )

#view resulting DataFrame
print (df_big)

        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

결과는 세 개의 개별 DataFrame 각각의 모든 행을 포함하는 대규모 DataFrame입니다.

ignore_index=True 인수는 팬더에게 각 DataFrame의 원래 인덱스 번호를 무시하고 새 DataFrame에 대해 0에서 시작하는 새 인덱스를 생성하도록 지시합니다.

예를 들어, 다음 두 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
df_big = pd. concat ([df1,df2])

#view resulting DataFrame
print (df_big)

        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 DataFrame에 빈 열을 추가하는 방법
Pandas DataFrame에 열을 삽입하는 방법
Pandas DataFrame을 Excel로 내보내는 방법

의견을 추가하다

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