1

So i'm trying to append 2 np array together but it gives me this error ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)I know that this mean the shape of the array are not the same but I don't understand why and how to fix it.

arr1 = np.array([
 [10.24217065  5.63381577]
 [ 2.71521988 -3.33068004]
 [-3.43022486 16.40921457]
 [ 1.4461307  12.59851726]
 [12.34829023 29.67531647] 
 [16.65382971  9.8915765 ]])

arr2 = np.array([4.62643996 5.14587112])

arr3 = np.append(arr1,arr2,axis=0)
3
  • np.vstack((arr1,arr2)) Commented Jun 6, 2020 at 15:32
  • It should be obvious to you that arr1 is 2d with shape (6,2), and arr2 is 1d with shape (2,). If not, then you need to read some more numpy basics. Commented Jun 6, 2020 at 15:54
  • np.append with axis parameter just uses np.concatenate([ arg1, args2], axis=0). Concatenate is picky about the number of dimensions, and patching shapes. I'd recommend staying away from np.append, and learn enough about dimensions to use np.concatenate correctly. Commented Jun 6, 2020 at 15:58

4 Answers 4

1

Simply make them the same dimension:

arr3 = np.append(arr1, [arr2], axis=0)
Sign up to request clarification or add additional context in comments.

Comments

1

arr2 has only a single dimension, since its shape is (2,). arr1 on the other hand has two dimensions, since its shape is (6, 2). These aren't compatible for np.append, as it says.

You can make arr2 have the required number of dimensions in many ways. One of them is reshaping:

arr3 = np.append(arr1, arr2.reshape(1, 2), axis=0)

At this point, the arrays have shape (6, 2) and (1, 2), which np.append knows how to deal with. The output will have shape (7, 2).

Comments

1

The error message tells you exactly what is the problem. The first array has two dimensions and the second array has one dimension. Another pair of [ ] in the second array will do the job.

arr2 = np.array([[4.62643996 5.14587112]])

Comments

0
arr3 = np.vstack((arr1, arr2))

or if you really want to use append, my favorite is

arr3 = np.append(arr1, arr2[np.newaxis, :])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.