初始化一个 numpy 数组 [英] initialize a numpy array
问题描述
有没有办法初始化一个形状的 numpy 数组并添加到它?我将用一个列表示例来解释我需要什么.如果我想创建一个循环生成的对象列表,我可以这样做:
Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do:
a = []
for i in range(5):
a.append(i)
我想用 numpy 数组做类似的事情.我知道 vstack、concatenate 等.但是,这些似乎需要两个 numpy 数组作为输入.我需要的是:
I want to do something similar with a numpy array. I know about vstack, concatenate etc. However, it seems these require two numpy arrays as inputs. What I need is:
big_array # Initially empty. This is where I don't know what to specify
for i in range(5):
array i of shape = (2,4) created.
add to big_array
big_array
应该有一个形状 (10,4)
.如何做到这一点?
The big_array
should have a shape (10,4)
. How to do this?
我想添加以下说明.我知道我可以定义 big_array = numpy.zeros((10,4))
然后填充它.但是,这需要提前指定 big_array 的大小.我知道这种情况下的尺寸,但如果我不知道怎么办?当我们在python中使用.append
函数扩展列表时,我们不需要提前知道它的最终大小.我想知道是否存在类似的东西,用于从较小的数组创建一个较大的数组,从一个空数组开始.
I want to add the following clarification. I am aware that I can define big_array = numpy.zeros((10,4))
and then fill it up. However, this requires specifying the size of big_array in advance. I know the size in this case, but what if I do not? When we use the .append
function for extending the list in python, we don't need to know its final size in advance. I am wondering if something similar exists for creating a bigger array from smaller arrays, starting with an empty array.
推荐答案
返回给定形状的新数组并类型,用零填充.
Return a new array of given shape and type, filled with zeros.
或
返回给定形状的新数组并类型,填充一个.
Return a new array of given shape and type, filled with ones.
或
返回给定形状的新数组并类型,无需初始化条目.
Return a new array of given shape and type, without initializing entries.
<小时>
然而,通过将元素附加到列表来构造数组的心态在 numpy 中并没有得到太多使用,因为它的效率较低(numpy 数据类型更接近底层的 C 数组).相反,您应该将数组预先分配到您需要的大小,然后填充行.不过,如果必须,您可以使用 numpy.append
.
这篇关于初始化一个 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!