Easy Tutorial
❮ Home Numpy Install ❯

NumPy Array Creation

Besides using the underlying ndarray constructor to create ndarray arrays, they can also be created through the following methods.

numpy.empty

The numpy.empty method is used to create an array of a specified shape and data type that is not initialized:

numpy.empty(shape, dtype=float, order='C')

Parameter Description:

Parameter Description
shape Array shape
dtype Data type, optional
order Options are 'C' for row-major (C-style) or 'F' for column-major (Fortran-style) order in memory.

Here is an example of creating an empty array:

Example

import numpy as np
x = np.empty([3,2], dtype=int)
print(x)

Output result:

[[ 6917529027641081856  5764616291768666155]
 [ 6917529027641081859 -5764598754299804209]
 [          4497473538      844429428932120]]

Note − The array elements are random values because they are not initialized.

numpy.zeros

Creates an array of a specified size, filled with zeros:

numpy.zeros(shape, dtype=float, order='C')

Parameter Description:

Parameter Description
shape Array shape
dtype Data type, optional
order 'C' for C-style row array, or 'F' for Fortran-style column array

Example

import numpy as np

# Default is float
x = np.zeros(5)
print(x)

# Set type to integer
y = np.zeros((5,), dtype=int)
print(y)

# Custom type
z = np.zeros((2,2), dtype=[('x', 'i4'), ('y', 'i4')])
print(z)

Output result:

[0. 0. 0. 0. 0.]
[0 0 0 0 0]
[[(0, 0) (0, 0)]
 [(0, 0) (0, 0)]]

numpy.ones

Creates an array of a specified shape, filled with ones:

numpy.ones(shape, dtype=None, order='C')

Parameter Description:

Parameter Description
shape Array shape
dtype Data type, optional
order 'C' for C-style row array, or 'F' for Fortran-style column array

Example

import numpy as np

# Default is float
x = np.ones(5)
print(x)

# Custom type
x = np.ones([2,2], dtype=int)
print(x)

Output result:

[1. 1. 1. 1. 1.]
[[1 1]
 [1 1]]
❮ Home Numpy Install ❯