Adam - 11 months ago 101

Python Question

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:

#i=[2 2 2 ] #for example

h=i*Weights

#h=[[8 8 8][8 8 8][8 8 8]]

All=np.concatenate((All,h),axis=0)

I ge this error:

`ValueError: all the input arrays must have same number of dimensions`

I want "All" variable to be

`[[8 8 8][8 8 8][8 8 8] [12 12 12][12 12 12][12 12 12]]`

Any way how I can add "h" to "All" through the loop ?

Answer Source

*Option 1*:
Reshape your initial `All`

array to 3 columns so that the number of columns match `h`

:

```
All=np.array([]).reshape((0,3))
for i in data:
h=i*Weights
All=np.concatenate((All,h))
All
#array([[ 8., 8., 8.],
# [ 8., 8., 8.],
# [ 8., 8., 8.],
# [ 12., 12., 12.],
# [ 12., 12., 12.],
# [ 12., 12., 12.]])
```

*Option 2*:
Use a if-else statement to handle initial empty array case:

```
All=np.array([])
for i in data:
h=i*Weights
if len(All) == 0:
All = h
else:
All=np.concatenate((All,h))
All
#array([[ 8, 8, 8],
# [ 8, 8, 8],
# [ 8, 8, 8],
# [12, 12, 12],
# [12, 12, 12],
# [12, 12, 12]])
```

*Option 3*:
Use `itertools.product()`

:

```
import itertools
np.array([i*j for i,j in itertools.product(data, Weights)])
#array([[ 8, 8, 8],
# [ 8, 8, 8],
# [ 8, 8, 8],
# [12, 12, 12],
# [12, 12, 12],
# [12, 12, 12]])
```