Concatenate/stack unpacked numpy array in certain axis to other arrays
<p>I want to create a numpy array <code>variables</code> with a certain structure, as in the example below, consisting of the variables <code>X</code> and <code>Y</code> for a meshgrid and additional parameters <code>params</code>. I need this in the context of plotting a 3D surface plot for a function <code>f(variables)</code>.</p>

<p>This is how the <code>variables</code> array should look like with some arbitrary <code>params</code> 5, 5, 5.</p>

<pre><code>import numpy as np

X = np.linspace(0, 2, num=3)
Y = np.linspace(0, 2, num=3)
X, Y = np.meshgrid(X, Y)
variables = np.array([X, Y, 5, 5, 5])
print(variables)
</code></pre>

<p>With the desired output:</p>

<pre><code>array([[[ 0.,  1.,  2.],
        [ 0.,  1.,  2.],
        [ 0.,  1.,  2.]],
       [[ 0.,  0.,  0.],
        [ 1.,  1.,  1.],
        [ 2.,  2.,  2.]],
       5, 5, 5])
</code></pre>

<p>And my questions is how can I construct this when having the parameters 5, 5, 5 in a numpy array also. (And explicitly not having something like <code>[X, Y, [5, 5, 5]]</code>.)</p>

<pre><code>params = np.array([5, 5, 5])
</code></pre>

<p>I already looked at different numpy functions like stack or concatenate, but could not figure it out. I'm rather new to numpy, so thanks for any help.</p>

<p>You can't get there from here.</p>

<p>Numpy arrays are for storing cuboidal grids of data, where each entry is the same shape as every other entry.</p>

<p>The best you can do here is have a <code>(5,)</code>-grid, containing <code>object</code>s, where each of the first two objects is itself a numpy array:</p>

<pre><code>params = np.array([5, 5, 5])
XY = np.array([X, Y, None])[:-1]  # trick numpy into using a 1d object array
                                  # there might be a better way to do this
variables = np.concatenate((XY, params))
variables

array([array([[ 0.,  1.,  2.],
       [ 0.,  1.,  2.],
       [ 0.,  1.,  2.]]),
       array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.],
       [ 2.,  2.,  2.]]),
       5, 5, 5], dtype=object)
</code></pre>

<p>Are you sure you need a numpy array at all here? Is this enough:</p>

<pre><code>variables = (X, Y) + tuple(params)
</code></pre>

python arrays numpy