numpy mask for 2d array with all values in 1d array
<p>I want to convert a 2d matrix of dates to boolean matrix based on dates in a 1d matrix. i.e., </p>

<pre><code>[[20030102, 20030102, 20070102],
 [20040102, 20040102, 20040102].,
 [20050102, 20050102, 20050102]] 
</code></pre>

<p>should become</p>

<pre><code>[[True, True, False],
 [False, False, False].,
 [True, True, True]] 
</code></pre>

<p>if I provide a 1d array [20010203, <strong>20030102</strong>, 20030501, <strong>20050102</strong>, 20060101]</p>

<pre><code>a = np.array([[20030102, 20030102, 20070102],
              [20040102, 20040102, 20040102],
              [20050102, 20050102, 20050102]])

b = np.array([20010203, 20030102, 20030501, 20050102, 20060101])

&gt;&gt;&gt; a.shape
(3, 3)
&gt;&gt;&gt; b.shape
(5,)
&gt;&gt;&gt;
</code></pre>

<p>For the comparison, you need to <a href="https://docs.scipy.org/doc/numpy-dev/user/basics.broadcasting.html" rel="nofollow">broadcast</a> <code>b</code> onto <code>a</code> by adding an axis to <code>a</code>. - this compares each element of <code>a</code> with each element of <code>b</code></p>

<pre><code>&gt;&gt;&gt; mask = a[...,None] == b
&gt;&gt;&gt; mask.shape
(3, 3, 5)
&gt;&gt;&gt; 
</code></pre>

<p>Then use <code>np.any()</code> to see if there are any matches</p>

<pre><code>&gt;&gt;&gt; np.any(mask, axis = 2, keepdims = False)
array([[ True,  True, False],
       [False, False, False],
       [ True,  True,  True]], dtype=bool)
</code></pre>

<hr>

<p>timeit.Timer comparison with <code>in1d</code>:</p>

<pre><code>&gt;&gt;&gt; 
&gt;&gt;&gt; t = Timer("np.any(a[...,None] == b, axis = 2)","from __main__ import np, a, b")
&gt;&gt;&gt; t.timeit(10000)
0.13268041338812964
&gt;&gt;&gt; t = Timer("np.in1d(a.ravel(), b).reshape(a.shape)","from __main__ import np, a, b")
&gt;&gt;&gt; t.timeit(10000)
0.26060646913566643
&gt;&gt;&gt;
</code></pre>

python numpy