初始化的空numpy数组实际上不是空的(包含零)

[英]Initialized empty numpy array is not really empty (contains zeros)


In order to store many 3D points coordinates tuples in a numpy.ndarray I initialize an empty numpy array before entering a loop for each of some features.

为了在numpy.ndarray中存储许多3D点坐标元组,我在为每个特征输入循环之前初始化一个空的numpy数组。

To do so, I currently do this before entering the loop:

为此,我目前在进入循环之前执行此操作:

import numpy as np
pointsarrray = np.empty((1,3))

but this results in an array which is all but empty:

但这会产生一个几乎为空的数组:

array([[  5.30498948e-315,   0.00000000e+000,   7.81250000e-003]])

When filling pointsarray in my loop after, I do this:

当我在循环中填充pointsarray之后,我这样做:

pointsarray = np.vstack((pointsarray, [np.array(myPoint)]))

(it also works with np.append)

(它也适用于np.append)

and I finally need to delete the first line of the array after exiting the loop because this first line always contains the values from the initialization step!

我最后需要在退出循环后删除数组的第一行,因为第一行总是包含初始化步骤中的值!

It's not a big deal but I wonder if there is a cleaner way to achieve a really empty array, I mean; with nothing inside it (it shows 1 row yet, I can not figure out why) but at the right dimensions?

这不是什么大问题,但我想知道是否有一种更清洁的方法来实现一个真正空的阵列,我的意思是;里面没有任何东西(它显示1行,我无法弄清楚为什么)但是在正确的尺寸?

2 个解决方案

#1


5  

You need the shape to be (0, 3) so you have the correct number of columns to stack but have actually no data inside:

您需要将形状设置为(0,3),以便您具有要堆叠的正确列数,但实际上没有数据:

import numpy as np
pointsarrray = np.empty((0,3))

pointsarrray
# array([], shape=(0, 3), dtype=float64)

#2


2  

Maybe it's the name that is confusing you but numpy.emptys documentation explains what is happening:

也许这个名字令你感到困惑,但是numpy.emptys文档解释了发生了什么:

Return a new array of given shape and type, without initializing entries.

返回给定形状和类型的新数组,而不初始化条目。

So it just doesn't initialize the entries (sometimes they are random sometimes they are zero) but empty refers only to the value of the entries not to the shape of the array.

所以它只是没有初始化条目(有时它们是随机的,有时它们是零)但是空指的是条目的值而不是数组的形状。


However it's really bad for performance to create an array by appending or stacking. Just collect them in a list and create the array afterwards:

但是,通过追加或堆叠来创建阵列对于性能来说真的很糟糕。只需在列表中收集它们并在之后创建数组:

pointsarray = [np.array(myPoint)]

# ...

pointsarray = np.array(pointsarray)  # or np.stack(pointsarray, axis=...) whatever you need.

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/06/07/88974f3bb42f2e7463bda3f89ec245e.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号