NumPy Create an Empty Array or Matrix: A Beginner Guide – NumPy Tutorial

By | May 16, 2020

Empty array and matrix is an important data in numpy. In this tutorial, we will introduce how to create them using some simple examples.

Can numpy.empty() create an empty array?

The answer is not, numpy.empty() function can not create an empty array.

Here is detail.

Understand numpy.empty(): It Cannot Create an Empty NumPy Array

How to create an empty array?

To create an empty array is very easy in numpy. Here is an example:

import numpy as np

ex = np.array([], dtype = np.float32)
print(ex)
print(ex.shape)

The ex is:

[]
(0,)

How to check a numpy array is empty or not?

We can use ndarray.size to check. Here is an tutorial.

Check a NumPy Array is Empty or not: A Beginner Tutorial

Concatenate numpy empty array with other non-empty array

This is an very import tip for numpy programming. We can concatenate an empty array with other non-empty numpy array. Here is an example:

x2 = np.array([1, 2, 3, 4], dtype = np.float32)
x = np.concatenate((ex, x2), axis = 0)
print(x)

Here ex is an empty array, x2 is not empty. We can concatenate them. The result x is:

[1. 2. 3. 4.]

Similar to empty array, we also can create an empty matrix in numpy.

How to create an empty matrix

We can create an empty numpy matrix as code below:

import numpy as np

em = np.mat([], dtype = np.float32)
print(em)
print(em.shape)

Here em is an empty numpy matrix. We also can use em.size to check a numpy matrix is empty or not.

em is:

[]
(1, 0)

Notice: you should notice the shape of empty array ex and empty matrix em is not.

ex (0,)
em (1,0)

Leave a Reply

Your email address will not be published. Required fields are marked *