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)
3
  • 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. Commented Nov 30, 2020 at 7: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. Commented Nov 30, 2020 at 7:59
  • @hpaulj I got it now, my bad for poorly interpreting the syntax of np.append(). Commented Nov 30, 2020 at 8:41

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Thanks, the logic is clear, had a cultural shock that append does not work the same way as the one in list.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.