I'm trying to create a new array out of two other arrays. I already tried multiple np.append() statements along multiple axis. Here is some code:
arr1 = np.zeros(2, 3)
arr2 = np.zeros(2, 2)
new_arr = np.append(arr1, arr2)
print(new_arr)
Desired output:
[
[[0, 0, 0], [0, 0, 0]],
[[0, 0], [0, 0]]
]
Actual output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
asked Jan 20, 2021 at 7:20
-
Does this answer your question? How do I stack vectors of different lengths in NumPy?anurag– anurag2021年01月20日 07:54:35 +00:00Commented Jan 20, 2021 at 7:54
-
Do you want to have the 2*2 array in the same line as 2*3 array or in the other line?QuantumOscillator– QuantumOscillator2021年01月20日 07:56:05 +00:00Commented Jan 20, 2021 at 7:56
2 Answers 2
try this
import numpy as np
arr1 = np.array([0, 0, 0])
arr2 = np.array([0, 0, 0])
final_arr = np.concatenate((arr1, arr2))
print(final_arr)
Refer this --> https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html
answered Jan 20, 2021 at 7:22
Sign up to request clarification or add additional context in comments.
1 Comment
melonmarlon
That only works if both arrays have the same shape. Otherwise you get the following:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 2
You can do it this way:
np.asarray([list(arr1),list(arr2)], dtype = 'O')
The dtype = 'O'
means Object
type.
answered Jan 20, 2021 at 7:32
2 Comments
melonmarlon
Why is it so complicated? Why does numpy append arrays so wierdly?
Pablo C
@melonmarlon because it isn't made to work this way. From the docs: "An array object represents a multidimensional, homogeneous array of fixed-size items" (numpy.org/doc/stable/reference/generated/numpy.ndarray.html)
lang-py