Fastest way to build a Matrix with a custom architecture
<p>What's the fastest way in numpy or pandas to build a matrix that has this form:</p>

<pre><code>1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
</code></pre>

<p>That preserves both odd and even architectures?</p>

<p>Using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy brodacasting</code></a>!</p>

<pre><code>In [289]: a = np.array([1,2,3,2,1])

In [290]: np.minimum(a[:,None],a)
Out[290]: 
array([[1, 1, 1, 1, 1],
       [1, 2, 2, 2, 1],
       [1, 2, 3, 2, 1],
       [1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1]])
</code></pre>

<p>To build the range array, we can do something like this -</p>

<pre><code>In [303]: N = 3

In [304]: np.concatenate((np.arange(1,N+1),np.arange(N-1,0,-1)))
Out[304]: array([1, 2, 3, 2, 1])
</code></pre>

<p><strong>Adding some bias</strong></p>

<p>Let's say we want to move the highest number/peak up or down. We need to create another <em>biasing</em> array and use the same strategy of <code>broadcasting</code>, like so -</p>

<pre><code>In [394]: a = np.array([1,2,3,2,1])

In [395]: b = np.array([2,3,2,1,0]) # Biasing array

In [396]: np.minimum(b[:,None],a)
Out[396]: 
array([[1, 2, 2, 2, 1],
       [1, 2, 3, 2, 1],
       [1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1],
       [0, 0, 0, 0, 0]])
</code></pre>

<p>Similarly, to have the bias shifted left or right, modify <code>a</code>, like so -</p>

<pre><code>In [397]: a = np.array([2,3,2,1,0]) # Biasing array

In [398]: b = np.array([1,2,3,2,1])

In [399]: np.minimum(b[:,None],a)
Out[399]: 
array([[1, 1, 1, 1, 0],
       [2, 2, 2, 1, 0],
       [2, 3, 2, 1, 0],
       [2, 2, 2, 1, 0],
       [1, 1, 1, 1, 0]])
</code></pre>

python pandas numpy