1

I met with a problem when doing appending in NumPy. array_1 will throw an error: ValueError: could not broadcast input array from shape (4) into shape (3) but the bottom one does not, where am I doing it wrong? I need to write a loop to append arrays to each array in array_1.

The blunt way is to convert my 2d-arrays to a 2d-list, but as a keen learner, I am really curious about how to do it properly.

array_1 = np.array([[1,2,3], [4,5,6]])
array_1[0] = np.append(array_1[0], 1)

array_2 = np.array([[1,2,3]])
array_2 = np.append(array_2, 1)
ilovewt
  • 911
  • 2
  • 10
  • 18
  • 1
    "[The top example raises an exception]... but the bottom one does not, where am I doing it wrong?" Well, look at what's different between the two examples, in the first, you assign to `array_1[0]`; in the second, you assign to `array_2`. So, the first one tries to jam a row of 4 elements into an array that has rows 3 elements long. The second one simply reuses the name `array_2` for the row, throwing the original array away. "I need to write a loop to" In general, no, you don't; that's why you are using NumPy. – Karl Knechtel Nov 30 '20 at 07:59
  • 1
    STOP! `np.append` is a poorly named and conceived function. It is not, I repeat, not, a list append clone. It is just a cover function for `np.concatenate`. In the first example, you cannot change the shape of a numpy array row by row. You have to make a whole new array (no in-place operations) as in the second. – hpaulj Nov 30 '20 at 07:59
  • @hpaulj I got it now, my bad for poorly interpreting the syntax of `np.append()`. – ilovewt Nov 30 '20 at 08:41

1 Answers1

0

Change it to this:

array_1 = np.array([[1,2,3], [4,5,6]])
array_1 = [np.append(array_1[0], 1), array_1[1]]
  • Nice! Thanks, the logic is clear, had a cultural shock that `append` does not work the same way as the one in `list`. – ilovewt Nov 30 '20 at 07:38
  • You can't just `.append` whereever you'd like in a Numpy array in-place, because the array *must be rectangular at all times*. So the method is defined not to work in-place. – Karl Knechtel Nov 30 '20 at 08:00