2017-05-10 3 views
0

あるデータフレームの行の値が別のデータフレームの特定の列に含まれていないかどうかを確認したい場合は、データフレームの行の値が別のデータフレームの列に含まれていないことを確認してください

私のデータフレームがある場合:その値はDF2のCOL1に含まれていない場合

df1: 
    col1 col2 
0 a e 
1 b f 
2 c g 
3 d h 

df2: 

    col1 col2 
0 a y 
1 v u 
2 x z 
3 w t 

は、私がDF1のcol1にすべての行を反復処理し、チェックしたい

私の現在のコードは次のとおりです。

for row, i in df1.iterrows(): 
    for row, j in df2.iterrows(): 
     if i.col1 not in j.col1: 
      print("blu") 

は今のコードでは、DF1のCOL1の値は任意の助けが理解されるであろう

DF2のCOL1に含まれているにもかかわらず、もし条件を入力します。

答えて

0

は遅いので、iterrowsでループを最もよく避けています。そのため、ベクトル化されたpandasまたはnumpyファンクションを使用する方が優れています。

列に存在していないかどうか確認が必要な場合 - 反転ブールマスクに~isinを使用します。

mask = ~np.in1d(df1.col1,df2.col1) 
print (mask) 
[False True True True] 

行ごとにチェックする必要がある場合:

mask = ~df1.col1.isin(df2.col1) 
print (mask) 

0 False 
1  True 
2  True 
3  True 
Name: col1, dtype: bool 

代替ソリューションはnumpy.in1dを使用しています!=またはne

を使用してください
mask = df1.col1 != df2.col1 
#same as 
#mask = df1.col1.ne(df2.col1) 
print (mask) 

0 False 
1  True 
2  True 
3  True 
Name: col1, dtype: bool 

または:numpy.where

mask = df1.col1.values != df2.col1.values 
print (mask) 
[False True True True] 

そして、マスクによって新しい列がある場合は使用の可能性:

df1['new'] = np.where(mask, 'a', 'b') 
print (df1) 
    col1 col2 new 
0 a e b 
1 b f a 
2 c g a 
3 d h a 

差がより良いビットに見られる異なるDataFrames

print (df1) 
    col1 col2 
0 a e 
1 b f 
2 c g 
3 d h 

print (df2) 
    col1 col2 
0 a y 
1 v u 
2 d z <- change value to d 
3 w t 


mask = df1.col1 != df2.col1 
print (mask) 
0 False 
1  True 
2  True 
3  True 
Name: col1, dtype: bool 

mask = ~df1.col1.isin(df2.col1) 
print (mask) 
0 False 
1  True 
2  True 
3 False 
Name: col1, dtype: bool 

numpyのソリューションは明らかに速いです:

In [23]: %timeit (~df1.col1.isin(df2.col1)) 
The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 
10000 loops, best of 3: 198 µs per loop 

In [24]: %timeit (~np.in1d(df1.col1,df2.col1)) 
The slowest run took 9.25 times longer than the fastest. This could mean that an intermediate result is being cached. 
10000 loops, best of 3: 42.5 µs per loop 
+0

、偉大な答えをいただき、ありがとうございます。すべてのソリューションは、値が列にあるかどうかを判断するために働いていますが、 "if"のような条件付きでこれを使用しようとすると、次のエラーが発生します:Seriesの真理値はあいまいです。 a.empty、a.bool()、a.item()、a.any()またはa.all()を使用します。 –

+0

少なくとも1つの値が 'if mask.any()によってtrueの場合、chechにはanyを追加する必要があります:少なくとも1つを出力してくださいTrue'' – jezrael

+0

もっとよく説明してください[http://stackoverflow.com/questions/] 42071684/if-condition-for-between-2-data-frames-in-python)の答えです。 – jezrael

0

使用isinパンダで

df1.col1.isin(df2.col1) 

0  True 
1 False 
2 False 
3 False 
Name: col1, dtype: bool 
関連する問題