Below is my code where I'm trying to append 2 1D arrays to a 1 1D array:
import numpy as np
import random
arr = np.random.randint(10, size=(1,))
arr1 = np.random.randint(20, size=(1,))
arr2 = np.random.randint(30, size=(1,))
print(arr)
print(arr1)
print(arr2)
aparr = np.append(arr, arr1, arr2)
print(aparr)
However, I'm getting an error saying:
21 print(arr2)
22
---> 23 aparr = np.append(arr, arr1, arr2)
24 print(aparr)
<__array_function__ internals> in append(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/numpy/lib/function_base.py in append(arr, values, axis)
4669 values = ravel(values)
4670 axis = arr.ndim-1
-> 4671 return concatenate((arr, values), axis=axis)
4672
4673
<__array_function__ internals> in concatenate(*args, **kwargs)
TypeError: only integer scalar arrays can be converted to a scalar index
Not sure, what am I missing/doing wrong. Can someone please take a look and point/explain the mistake by correcting the piece of code?
CodePudding user response:
np.append() takes two arguments, an array to append to and a list of values to append to it. So, replace
aparr = np.append(arr, arr1, arr2)
by
aparr = np.append(arr, [arr1, arr2])
and it should work.
CodePudding user response:
I believe the command you are looking for is called np.concatenate
That is what is commonly used to combine multiple arrays into one array of the same dimension.
arr = np.random.randint(10, size=(10,))
arr1 = np.random.randint(20, size=(10,))
arr2 = np.random.randint(30, size=(5,))
combined = np.concatenate([arr, arr1, arr2]) # will be of size 25
notice that all the arrays are in one list (can be tuple or something else, as long as it is passed as one variable to the function).
It is possible to use np.append
, but that is just a limited version of np.concatenate
as can be seen in the source code, and it only works when combining exactly two arrays, so you would have to do it in two steps or by combining the two arrays which should be added:
combined = np.append(np.append(arr, arr1), arr2)
# OR
combined = np.append(arr, [arr1, arr2])
The final alternative works because the arrays are flattened before combining, because axis
(what dimension to combine the two arrays along) is not specified.