python零基于另一个的数组:相同的形状,但沿着一个维度更长

时间:2014-02-16 13:17:41

标签: python numpy

我有变量,其中维度的数量可以是大于2的任何值。对于每个变量,我想用一个具有相同形状但沿着第一维度更长的零来初始化一个新变量,即10倍。

import numpy as np
variable = np.ones([4, 5, 6])    #  This is just an example; in reality variable is generated
                                 #+ from data contained in files with np.genfromtxt, and the
                                 #+ number of dimensions can be anything greater than two

new_var = np.zeros([variable.shape[0] * 10, variable[0].shape])
                                 #  my above attempt does not work because variable[0].shape
                                 #+ returns a tuple and the result of what's given as argument
                                 #+ to np.zeros is [4, (5, 6)]

2 个答案:

答案 0 :(得分:1)

构建形状元组时需要注意:

new_shape = (variable.shape[0] * 10,) + variable.shape[1:]

然后你可以做

new_var = np.zeros(new_shape)

答案 1 :(得分:1)

IIUC,你可以简单地连接元组:

>>> v = np.ones([4,5,6])
>>> new_v = np.zeros((v.shape[0]*10,)+v.shape[1:])
>>> new_v.shape
(40, 5, 6)