1

I am trying to merge a sliced array to a list in Python but i get an

 error: ValueError: operands could not be broadcast together with shapes `(4,)` `(2,)` . 

This is my code:

y = np.array([5,3,2,4,6,1])
row = y[2:6] + np.array([0,0])

I am expecting to get a 2-item shifted vector to the left and last 2 items being assigned to 0.

hpaulj
  • 221,503
  • 14
  • 230
  • 353

4 Answers4

1

Numpy array works something like a matrix. So when you try to apply the addition operation to a numpy array, you're actually performing an "element-wise addition". That's why the value you add with a numpy array must be the same dimension as the numpy array. Otherwise such a value that can be broadcasted.

Notice the example to understand what I'm saying.

Adding two lists with addition sign:

>>> [1,2] + [3,4]
[1, 2, 3, 4]

Adding two numpy arrays:

>>> np.array([1,2]) + np.array([3,4])
array([4, 6])

To get your work done, use the np.append(arr, val, axis) function. Documentation

array([1, 2, 3, 4])
>>> np.append([1,2], np.array([3,4]))
array([1, 2, 3, 4])
Fahim
  • 308
  • 1
  • 3
  • 10
1

To concatenate arrays use np.concatenate:

In [93]: y = np.array([5,3,2,4,6,1])
In [94]: y[2:6]
Out[94]: array([2, 4, 6, 1])
In [95]: np.concatenate((y[2:6], np.array([0,0])))
Out[95]: array([2, 4, 6, 1, 0, 0])

+ is concatenate for lists. For arrays is addition (numeric sum).

Your question should not have used list and array in a sloppy manner. They are different things (in python/numpy) and can produce confusing answers.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

For concatenation, you will need to convert your numpy array to a list first.

row = y[2:6] + list(np.array([0,0]))

or equivalently

row = y[2:6] + np.array([0,0]).tolist()

However, if you wish to add the two (superpose a list and numpy array), then the numpy array just needs to be the same shape as y[2:6]:

In : y[2:6] + np.array([1, 2, 3, 4])
Out: array([y[2] + 1, y[3] + 2, y[4] + 3, y[5] + 4])
LPR
  • 400
  • 1
  • 8
0

Other answers already explain why your code fail. You can do:

out = np.zeros_like(y)
out[:-2] = y[2:]

Output:

array([2, 4, 6, 1, 0, 0])
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74