LoginSignup
44
27

More than 5 years have passed since last update.

[Python] Pandas のデータフレームの他のデータフレームと特定列が一致しないものを抽出

Posted at

これを書く

結論を先に書いてしまうとこうです。

df3 = df1[~df1['row1'].isin(df2['row2'])]

こういうことをやりたい

あるデータフレームdf1から、
そのデータフレームのもつcolumn 'row1'と、
比較対象データフレームdf2のもつcolumn 'row2'を比較し、
row2には存在しないrow1をもつ行をdf1から抽出したい。

SQLで書くとこうです。

SELECT * FROM df1
WHER df1.row1 NOT IN (SELECT row2 FROM df2)

df1のデータ

color row1
red eagle
blue shark
yellow lion
green elephant
white tiger
black world

df2のデータ

name row2
Sela shark
Leo lion
Tusk elephant
Amu tiger

df1から取り出したいデータ

color row1
red eagle
black world

実装

Zyuohger.py
import pandas as pd
df1 = pd.DataFrame({
        'color':['red',  'blue', 'yellow','green',   'white','black',],
        'row1' :['eagle','shark','lion',  'elephant','tiger','world',],
    })
df2 = pd.DataFrame({
        'name':['Sela', 'Leo', 'Tusk',    'Amu',],
        'row2':['shark','lion','elephant','tiger',],
    })

df3 = df1[~df1['row1'].isin(df2['row2'])]

print df3

結果

実行すると次のようになります。

$ python Zyuohger.py
   color   row1
0    red  eagle
5  black  world
44
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
27