如何将一个 numpy 矩阵附加到一个空的 numpy 数组中 [英] how to append a numpy matrix into an empty numpy array

查看:35
本文介绍了如何将一个 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

我希望所有"变量为

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

有什么办法可以通过循环将h"添加到All"吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆