パンダ: あるデータフレームの行が別のデータフレームに存在するかどうかを確認します


次の構文を使用して、各行が別の 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 の行が別の Pandas DataFrame に存在するかどうかを確認する

次の 2 つのパンダ 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

次の構文を使用して、各行のチーム列ポイント列の各値が 2 番目のデータフレームに存在するかどうかを示す、exists という名前の列を最初のデータフレームに追加できます。

 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

新しい列が存在することは、各行のチームおよびポイント列の各値が 2 番目のデータフレームに存在するかどうかを示します。

結果から次のことがわかります。

  • 2 番目のデータフレームには、チーム値Aとポイント値12が存在します。
  • チーム値Bとポイント値15 は、 2 番目のデータフレームには存在しません。
  • チーム値Cとポイント値22 は、 2 番目のデータフレームには存在しません。
  • 2 番目のデータフレームには、チーム値Dとポイント値29が存在します。
  • チーム値Eとポイント値24 は、 2 番目のデータフレームには存在しません。

また、NumPy Where()関数の値を変更することで、 exists列に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

既存の列の値が変更されていることに注意してください。

追加リソース

次のチュートリアルでは、パンダで他の一般的なタスクを実行する方法を説明します。

パンダ: あるデータフレームから別のデータフレームに列を追加します。
パンダ: 別の DataFrame にない行を取得する
パンダ: 複数の列が等しいかどうかを確認する方法

コメントを追加する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です