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)
array_1[0]; in the second, you assign toarray_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 namearray_2for 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.np.appendis a poorly named and conceived function. It is not, I repeat, not, a list append clone. It is just a cover function fornp.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.np.append().