Search code examples
pythonnumpyreshapenumpy-ndarrayvalueerror

Reshape np.array based on the default size


There are 2 np.arrays and I would like to reshape np.array1 from shape (12,)in reference to array2 with shape (4,):

array1 = np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) and array1.shape returns: (12,)

array2 = np.array([ 12, 34, 56, 78]) and array2.shape returns: (4,)

I tried to execute reshape:

array1.reshape(array2.shape)

But, there is an error: ValueError: cannot reshape array of size 12 into shape (4,)

So, Expected result is array1 with 4 elements: np.array([ 1, 2, 3, 4]), instead of 12.

I'd appreciate for any idea and help.


Solution

  • If I understand your requirements correctly, I think what you're looking for is simple slicing:

    In [140]: array2 = np.array([ 12,  34,  56,  78])
    In [135]: a_sliced =  array1[:array2.shape[0]]
    In [136]: a_sliced.shape
    Out[136]: (4,)
    

    If array2 is multi-dimensional, then use the approach suggested by Mad Physicist:

    sliced_arr = array1[tuple(slice(0, d) for d in array2.shape)]
    

    Alternatively, if you intended to split the array into three equal halves, then use numpy.split() as in:

    # split `array1` into 3 portions
    In [138]: np.split(array1, 3)
    Out[138]: [array([1, 2, 3, 4]), array([5, 6, 7, 8]), array([ 9, 10, 11, 12])]