Pandas: 한 dataframe의 행이 다른 dataframe에 있는지 확인


다음 구문을 사용하여 각 행이 다른 DataFrame에 있는지 여부를 나타내는 pandas DataFrame에 새 열을 추가할 수 있습니다.

 #merge two DataFrames on specific columns
all_df = pd. merge (df1, df2, on=[' column1 ', ' column2 '], how=' left ', indicator=' exists ')

#drop unwanted columns
all_df = all_df. drop (' column3 ', axis= 1 )

#add column that shows if each row in one DataFrame exists in another
all_df[' exists '] = np. where (all_df. exists == ' both ', True , False )

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

예: 한 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],
                    ' assists ': [4, 7, 7, 10, 12]})

print (df2)

  team points assists
0 to 12 4
1 D 29 7
2 F 15 7
3 G 19 10
4:10:12

다음 구문을 사용하여 의 각 값과 각 행의 포인트 열이 두 번째 DataFrame에 존재하는지 여부를 나타내는 존재라는 열을 첫 번째 DataFrame에 추가할 수 있습니다.

 import numpy as np

#merge two dataFrames and add indicator column
all_df = pd. merge (df1, df2, on=[' team ', ' points '], how=' left ', indicator=' exists ')

#drop assists columns
all_df = all_df. drop (' assists ', axis= 1 )

#add column to show if each row in first DataFrame exists in second
all_df[' exists '] = np. where (all_df. exists == ' both ', True , False )

#view updated DataFrame
print (all_df)

  team points exists
0 A 12 True
1 B 15 False
2 C 22 False
3 D 29 True
4 E 24 False

새로운 열 존재는 각 행의 포인트 열에 있는 각 값이 두 번째 DataFrame에 존재하는지 여부를 나타냅니다.

결과에서 우리는 다음을 볼 수 있습니다:

  • 두 번째 DataFrame에는 팀 값 A 와 포인트 값 12 가 존재합니다.
  • 두 번째 DataFrame에는 팀 값 B 와 포인트 값 15 가 존재하지 않습니다.
  • 두 번째 DataFrame에는 팀 값 C 와 포인트 값 22 가 존재하지 않습니다.
  • 두 번째 DataFrame에는 팀 값 D 와 포인트 값 29 가 존재합니다.
  • 두 번째 DataFrame에는 팀 값 E 와 포인트 값 24 가 존재하지 않습니다.

또한 NumPy Where() 함수의 값을 변경하여 존재 열에 True 및 False 이외의 값을 지정할 수도 있습니다.

예를 들어 다음과 같이 “존재함” 및 “존재하지 않음”을 대신 사용할 수 있습니다.

 #add column to show if each row in first DataFrame exists in second
all_df[' exists '] = np. where (all_df. exists == ' both ', ' exists ', ' not exists ')

#view updated DataFrame
print (all_df)

  team points exists
0 to 12 exists
1 B 15 not exists
2 C 22 not exists
3 D 29 exists
4 E 24 not exists

기존 열의 값이 변경되었으니 참고하세요.

추가 리소스

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

Pandas: 한 DataFrame의 열을 다른 DataFrame에 추가
Pandas: 다른 DataFrame에 없는 행 가져오기
Pandas:여러 열이 같은지 확인하는 방법

의견을 추가하다

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