如何将一个numpy矩阵附加到一个空的numpy数组中 [英] how to append a numpy matrix into an empty numpy array
本文介绍了如何将一个numpy矩阵附加到一个空的numpy数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过循环将numpy数组(矩阵)附加到数组中
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)
我会发生此错误:
ValueError: all the input arrays must have same number of dimensions
我希望"All"变量为
I want "All" variable to be
[[8 8 8][8 8 8][8 8 8] [12 12 12][12 12 12][12 12 12]]
如何通过循环将"h"添加到全部"?
Any way how I can add "h" to "All" through the loop ?
推荐答案
选项1 :
将初始的All
数组重塑为3列,以使列数与h
匹配:
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.]])
选项2 : 使用if-else语句处理初始空数组情况:
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]])
选项3 :
使用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]])
这篇关于如何将一个numpy矩阵附加到一个空的numpy数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文