简体   繁体   English

如何初始化Numpy数组的numpy数组

[英]How to initialise a Numpy array of numpy arrays

I have a numpy array D of dimensions 4x4 我有一个尺寸为4x4numpy array D

I want a new numpy array based on an user defined value v 我想要一个基于用户定义值v的新numpy数组

If v=2 , the new numpy array should be [DD] . 如果v=2 ,则新的numpy数组应为[DD] If v=3 , the new numpy array should be [DDD] 如果v=3 ,则新的numpy数组应为[DDD]

How do i initialise such a numpy array as numpy.zeros(v) dont allow me to place arrays as elements? 我如何将这样的numpy数组初始化为numpy.zeros(v)不允许我将数组作为元素放置?

If I understand correctly, you want to take a 2D array and tile it v times in the first dimension? 如果我理解正确,您想获取一个2D数组并将其在第一个维度上平铺v次吗? You can use np.repeat : 您可以使用np.repeat

# a 2D array
D = np.arange(4).reshape(2, 2)

print D
# [[0 1]
#  [2 3]]

# tile it 3 times in the first dimension
x = np.repeat(D[None, :], 3, axis=0)

print x.shape
# (3, 2, 2)

print x
# [[[0 1]
#   [2 3]]

#  [[0 1]
#   [2 3]]

#  [[0 1]
#   [2 3]]]

If you wanted the output to be kept two-dimensional, ie (6, 2) , you could omit the [None, :] indexing (see this page for more info on numpy's broadcasting rules). 如果希望输出保持二维,即(6, 2) 6,2 (6, 2) ,则可以省略[None, :]索引(有关numpy广播规则的更多信息,请参见此 )。

print np.repeat(D, 3, axis=0)
# [[0 1]
#  [0 1]
#  [0 1]
#  [2 3]
#  [2 3]
#  [2 3]]

Another alternative is np.tile , which behaves slightly differently in that it will always tile over the last dimension: 另一个选择是np.tile ,其行为略有不同,因为它将始终平铺在最后一个维度上:

print np.tile(D, 3)
# [[0, 1, 0, 1, 0, 1],
#  [2, 3, 2, 3, 2, 3]])

You can do that as follows: 您可以按照以下步骤进行操作:

import numpy as np
v = 3
x = np.array([np.zeros((4,4)) for _ in range(v)])

>>> print x
[[[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]

 [[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]

 [[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]]

Here you go, see if this works for you. 在这里,看看是否适合您。

import numpy as np
v = raw_input('Enter: ')

To intialize the numpy array of arrays from user input (obviously can be whatever shape you're wanting here): 从用户输入初始化数组的numpy数组(显然可以是您想要的任何形状):

b = np.zeros(shape=(int(v),int(v)))

I know this isn't initializing a numpy array but since you mentioned wanting an array of [DD] if v was 2 for example, just thought I'd throw this in as another option as well. 我知道这不是在初始化一个numpy数组,但是由于您提到例如要在v为2的情况下想要[DD]数组,所以以为我也将其作为另一个选择。

new_array = []
for x in range(0, int(v)):
    new_array.append(D)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM