NumPy ones()

Created with Sketch.

NumPy ones()

Summary: in this tutorial, you’ll learn how to use the numpy ones() function to create a numpy array of a given shape whose elements are filled with ones.

The ones() function of the numpy module allows you to create a numpy array of a given shape whose elements are filled with ones.

For example, the following uses the ones() function to create an array with three axes, the first axis has two elements, the second axis has three elements, and the third axis has 4 elements:

import numpy as np

a = np.ones((2, 3, 2))
print(a)

Code language: Python (python)

Output:

[[[1. 1.]
[1. 1.]
[1. 1.]]

[[1. 1.]
[1. 1.]
[1. 1.]]]

Code language: Python (python)

By default, ones() function uses float64 for its elements. For example:

import numpy as np

a = np.ones((2, 3, 2))
print(a.dtype)

Code language: Python (python)

Output:

float64

Code language: Python (python)

To use a different type, you need to specify it using the dtype argument. For example:

import numpy as np

a = np.ones((2, 3, 4), dtype=np.int32)
print(a)
print(a.dtype)

Code language: Python (python)

Output:

[[[1 1]
[1 1]
[1 1]]

[[1 1]
[1 1]
[1 1]]]
int32

Code language: Python (python)

In this example, we use int32 type for the elements. Therefore, you don’t see the decimal point (.) appearing on each number.

Summary

  • Use numpy ones() function to create an array of a given shape whose elements are filled with ones.

Leave a Reply

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