は遅いので、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
、偉大な答えをいただき、ありがとうございます。すべてのソリューションは、値が列にあるかどうかを判断するために働いていますが、 "if"のような条件付きでこれを使用しようとすると、次のエラーが発生します:Seriesの真理値はあいまいです。 a.empty、a.bool()、a.item()、a.any()またはa.all()を使用します。 –
少なくとも1つの値が 'if mask.any()によってtrueの場合、chechにはanyを追加する必要があります:少なくとも1つを出力してくださいTrue'' – jezrael
もっとよく説明してください[http://stackoverflow.com/questions/] 42071684/if-condition-for-between-2-data-frames-in-python)の答えです。 – jezrael