### 初始化的空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.

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 = 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?

## 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:

``````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.empty`s documentation explains what is happening:

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.
``````