두 개의 pandas dataframe을 추가하는 방법(예제 포함)
다음 기본 구문을 사용하여 두 개의 Pandas DataFrame에 값을 추가할 수 있습니다.
df3 = df1. add (df2, fill_value= 0 )
그러면 각 개별 DataFrame에서 일치하는 요소의 합계가 포함된 새 DataFrame이 생성됩니다.
한 DataFrame에는 요소가 있고 다른 DataFrame에는 없으면 기존 요소가 결과 DataFrame에 사용됩니다.
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: 두 개의 Pandas DataFrame을 추가하는 방법
다음 두 개의 팬더 DataFrame이 있다고 가정해 보겠습니다.
import pandas as pd #create first DataFrame df1 = pd. DataFrame ({' points ': [18, 22, 19, 14, 11], ' assists ': [5, 11, 7, 9, 12]}) #view first DataFrame print (df1) assist points 0 18 5 1 22 11 2 19 7 3 14 9 4 11 12 #create second DataFrame df2 = pd. DataFrame ({' points ': [10, 5, 4, 3, 9, 14], ' assists ': [9, 7, 4, 2, 3, 3]}) #view second DataFrame print (df2) assist points 0 10 9 1 5 7 2 4 4 3 3 2 4 9 3 5 14 3
다음 구문을 사용하여 각 개별 DataFrame에서 일치하는 요소의 합계를 취하는 새 DataFrame을 만들 수 있습니다.
#create new DataFrame by adding two DataFrames
df3 = df1. add (df2, fill_value= 0 )
#view new DataFrame
print (df3)
assist points
0 28.0 14.0
1 27.0 18.0
2 23.0 11.0
3 17.0 11.0
4 20.0 15.0
5 14.0 3.0
결과 DataFrame에는 각 개별 DataFrame에서 일치하는 요소의 합계가 포함됩니다.
참고로 인덱스 값이 5인 행은 두 번째 DataFrame에만 존재하므로 이 행의 값은 단순히 두 번째 DataFrame의 값입니다.
또한 추가를 수행했기 때문에 새 DataFrame의 각 값은 소수점 이하 한 자리의 부동 소수점 값으로 표시됩니다.
이러한 각 값을 다시 정수로 변환하려면 astype() 함수를 사용할 수 있습니다.
#convert all columns in new DataFrame to integer
df3 = df3. astype (' int64 ')
#view updated DataFrame
print (df3)
assist points
0 28 14
1 27 18
2 23 11
3 17 11
4 20 15
5 14 3
새 DataFrame의 각 값은 이제 정수입니다.
추가 리소스
다음 튜토리얼에서는 다른 일반적인 Panda 작업을 수행하는 방법을 설명합니다.
Pandas: 한 DataFrame의 열을 다른 DataFrame에 추가
Pandas: 다른 DataFrame에 없는 행 가져오기
Pandas:여러 열이 같은지 확인하는 방법