Pandas: 다른 dataframe에 없는 행 가져오기
다음 기본 구문을 사용하여 다른 DataFrame에 없는 Pandas DataFrame에서 행을 가져올 수 있습니다.
#merge two DataFrames and create indicator column df_all = df1. merge ( df2.drop_duplicates (), on=[' col1 ',' col2 '], how=' left ', indicator= True ) #create DataFrame with rows that exist in first DataFrame only df1_only = df_all[df_all[' _merge '] == ' left_only ']
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: 다른 DataFrame에 없는 Pandas DataFrame의 행 가져오기
다음 두 개의 팬더 DataFrame이 있다고 가정해 보겠습니다.
import pandas as pd #create first DataFrame df1 = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E'], ' points ': [12, 15, 22, 29, 24]}) print (df1) team points 0 to 12 1 B 15 2 C 22 3 D 29 4 E 24 #create second DataFrame df2 = pd. DataFrame ({' team ': ['A', 'D', 'F', 'G', 'H'], ' points ': [12, 29, 15, 19, 10]}) print (df2) team points 0 to 12 1 D 29 2 F 15 3 G 19 4:10 a.m.
다음 구문을 사용하여 두 DataFrame을 병합하고 각 DataFrame에 속하는 행을 나타내는 표시기 열을 만들 수 있습니다.
#merge two DataFrames and create indicator column df_all = df1. merge ( df2.drop_duplicates (), on=[' team ',' points '], how=' left ', indicator= True ) #view result print (df_all)
그런 다음 다음 구문을 사용하여 두 번째 DataFrame에 없는 첫 번째 DataFrame의 행만 가져올 수 있습니다.
#create DataFrame with rows that exist in first DataFrame only df1_only = df_all[df_all[' _merge '] == ' left_only '] #view DataFrame print (df1_only) team points _merge 1 B 15 left_only 2 C 22 left_only 4 E 24 left_only
마지막으로 원하는 경우 _merge 열을 제거할 수 있습니다.
#drop '_merge' column
df1_only = df1_only. drop (' _merge ', axis= 1 )
#view DataFrame
print (df1_only)
team points
1 B 15
2 C 22
4 E 24
결과는 모든 행이 첫 번째 DataFrame에 있지만 두 번째 DataFrame에는 없는 DataFrame입니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas에서 한 DataFrame의 열을 다른 DataFrame에 추가하는 방법
Pandas에서 열 순서를 변경하는 방법
Pandas에서 이름별로 열을 정렬하는 방법