I want to append a numpy array(matrix) into an array through a loop
data=[[2 2 2] [3 3 3]]
Weights=[[4 4 4] [4 4 4] [4 4 4]]
All=np.array([])
for i in data:
A preferred way of constructing an array with a loop is to collect values in a list, and perform the concatenate
once, at the end:
In [1025]: data
Out[1025]:
array([[2, 2, 2],
[3, 3, 3]])
In [1026]: Weights
Out[1026]:
array([[4, 4, 4],
[4, 4, 4],
[4, 4, 4]])
Append to a list is much faster than repeated concatenate
; plus it avoids the 'empty` array shape issue:
In [1027]: alist=[]
In [1028]: for row in data:
...: alist.append(row*Weights)
In [1029]: alist
Out[1029]:
[array([[8, 8, 8],
[8, 8, 8],
[8, 8, 8]]), array([[12, 12, 12],
[12, 12, 12],
[12, 12, 12]])]
In [1031]: np.concatenate(alist,axis=0)
Out[1031]:
array([[ 8, 8, 8],
[ 8, 8, 8],
[ 8, 8, 8],
[12, 12, 12],
[12, 12, 12],
[12, 12, 12]])
You can also join the arrays on a new dimension with np.array
or np.stack
:
In [1032]: np.array(alist)
Out[1032]:
array([[[ 8, 8, 8],
[ 8, 8, 8],
[ 8, 8, 8]],
[[12, 12, 12],
[12, 12, 12],
[12, 12, 12]]])
In [1033]: _.shape
Out[1033]: (2, 3, 3)
I can construct this 3d version with a simple broadcasted multiplication - no loops
In [1034]: data[:,None,:]*Weights[None,:,:]
Out[1034]:
array([[[ 8, 8, 8],
[ 8, 8, 8],
[ 8, 8, 8]],
[[12, 12, 12],
[12, 12, 12],
[12, 12, 12]]])
Add a .reshape(-1,3)
to that to get the (6,3) version.
np.repeat(data,3,axis=0)*np.tile(Weights,[2,1])
also produces the desired 6x3 array.