How To Repeatedly Concatenate Numpy Arrays?
I am trying to see if I can concatenate an empty array with fixed size with other arrays with the same size: import numpy as np final_array = np.empty([3, 5]) >>>final_ar
Solution 1:
np.vstack
may suffice for your purpose:
array_1 = np.array([1, 1, 1])
array_2 = np.array([2, 2, 2])
array_3 = np.array([3, 3, 3])
lst = [array_1, array_2, array_3]
np.vstack(lst)
# array([[1, 1, 1],
# [2, 2, 2],
# [3, 3, 3]])
An alternative is itertools.chain
:
from itertools import chain
np.fromiter(chain(*lst), dtype=np.int8).reshape((len(lst), len(lst[0])))
# array([[1, 1, 1],
# [2, 2, 2],
# [3, 3, 3]], dtype=int8)
Solution 2:
In [1]: final_array = np.empty([3, 5])
In [2]: final_array
Out[2]:
array([[-1.52691690e-041, 6.36598743e-314, 2.01589600e-312,
2.41907520e-312, 1.90979622e-313],
[ 6.79038654e-313, 6.79038653e-313, 3.18299369e-313,
2.14321575e-312, 2.37663529e-312],
[ 4.45619117e-313, 1.93101617e-312, 8.70018274e-313,
-1.52680304e-041, 8.70018275e-313]])
This is a (3,5) shaped array with random, 'unfilled' values.
In [3]: np.concatenate([final_array, np.array([1,1,1])])
ValueError: all the input arrays must have same number of dimensions
This doesn't work because final_array
is 2d, and the other is 1d.
In [4]: np.concatenate([final_array, np.array([[1,1,1]])])
ValueError: all the input array dimensions except for the concatenation axis must match exactly
Now the 2nd is (1,3), which doesn't match on the 2nd dimension with (3,5).
In [5]: np.concatenate([final_array, np.array([[1,1,1,1,1]])])
Out[5]:
array([[-1.52691690e-041, 6.36598743e-314, 2.01589600e-312,
2.41907520e-312, 1.90979622e-313],
[ 6.79038654e-313, 6.79038653e-313, 3.18299369e-313,
2.14321575e-312, 2.37663529e-312],
[ 4.45619117e-313, 1.93101617e-312, 8.70018274e-313,
-1.52680304e-041, 8.70018275e-313],
[ 1.00000000e+000, 1.00000000e+000, 1.00000000e+000,
1.00000000e+000, 1.00000000e+000]])
In [6]: _.shape
Out[6]: (4, 5)
This works, adding a new row to the original (3,5). But the original random values are still there.
It is better to build a list of arrays, and do one concatenate
In [7]: alist = [] # not at all like `np.empty`
In [8]: for i in range(3):
...: alist.append(np.ones((3,),int)*(i+1))
...:
In [9]: alist
Out[9]: [array([1, 1, 1]), array([2, 2, 2]), array([3, 3, 3])]
In [10]: np.array(alist)
Out[10]:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
In [11]: np.stack(alist) # equivalent
Out[11]:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
In [12]: np.vstack(alist)
Out[12]:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
But concatenate
joins them on the 1 existing dimension:
In [13]: np.concatenate(alist)
Out[13]: array([1, 1, 1, 2, 2, 2, 3, 3, 3])
Post a Comment for "How To Repeatedly Concatenate Numpy Arrays?"