How to create 0x0 Numpy array?

Question:

How do I create a 0 x 0 (i.e. ndim= 2, shape= (0,0)) float numpy.ndarray?

Asked By: Johan Råde

||

Answers:

>>> import numpy as np
>>> a = np.empty( shape=(0, 0) )
>>> a
    array([], shape=(0, 0), dtype=float64)

>>> a.shape
    (0, 0)
>>> a.size
    0

The array above is initialized as a 2D array–i.e., two size parameters passed for shape.

Second, the call to empty is not strictly necessary–i.e., an array having 0 size could (i believe) be initialized using other array-creation methods in NumPy, e.g., NP.zeros, Np.ones, etc.

I just chose empty because it gives the smallest array (memory-wise).

Answered By: doug

All of the functions that return an array given shape/size can create a 0x0 array (in fact, of any dimension).

np.full((0,0), 0.0)
np.random.rand(0,0)
np.random.randint(0, size=(0,0))
np.random.choice(0, size=(0,0))
# etc. 

To create the same with np.array, the shape attribute of an empty array could be modified.

a = np.array([])
a.shape += (0,)
a  # array([], shape=(0, 0), dtype=float64)
Answered By: cottontail
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.