Slice numpy array to make it desired shaped
<p>Surprisingly, couldn't find the answer across the internet. I have an n-dimensional numpy array. E.g.: 2-D np array:</p>

<pre><code>array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'],
       ['41.7900000', '44.8000000', '48.2600000', '46.1800000'],
       ['36.1200000', '37.1500000', '39.3100000', '38.1000000'],
       ['82.1000000', '82.0900000', '76.0200000', '77.7000000'],
       ['48.0100000', '51.2500000', '51.1700000', '52.5000000', '55.2500000'],
       ['39.7500000', '39.5000000', '36.8100000', '37.2500000']], dtype=object)
</code></pre>

<p>As you can see, the 5th row consists of 5 elemnts and <strong>i want to make the 5th dissapear</strong>, using something like this:</p>

<pre><code>np.slice(MyArray, [6,4]) 
</code></pre>

<p>[6,4] is a shape. I really DO not want to iterate threw dimensions and cut them. I tried the <code>resize</code> method, but it returns nothing!</p>

<p>Here's an almost* vectorized approach -</p>

<pre><code>def slice_2Dobject_arr(arr,out_shape):
    lens = np.array(map(len,arr))
    id_arr = np.ones(lens.sum(),dtype=int)
    id_arr[lens[:-1].cumsum()] = -lens[:-1]+1
    mask = id_arr.cumsum()&lt;=out_shape[1]
    vals = np.concatenate(arr)
    return vals[mask].reshape(-1,out_shape[1])[:out_shape[0]]
</code></pre>

<p>*: Almost because of the use of <code>map</code> at the start to get the lengths of the lists in the input array, which seems isn't a vectorized operation. But, computationally that should be comparatively negligible.</p>

<p>Sample runs -</p>

<pre><code>In [92]: arr
Out[92]: array([[3, 4, 5, 3], [3, 7, 8], [4, 9, 6, 4, 2], [3, 9, 4]], dtype=object)

In [93]: slice_2Dobject_arr(arr,(4,3))
Out[93]: 
array([[3, 4, 5],
       [3, 7, 8],
       [4, 9, 6],
       [3, 9, 4]])

In [94]: slice_2Dobject_arr(arr,(3,3))
Out[94]: 
array([[3, 4, 5],
       [3, 7, 8],
       [4, 9, 6]])

In [95]: slice_2Dobject_arr(arr,(3,2))
Out[95]: 
array([[3, 4],
       [3, 7],
       [4, 9]])
</code></pre>

python arrays numpy