NumPy Create array filled with all ones (original) (raw)

Last Updated : 24 Jan, 2025

To create an **array filled with all ones, given the shape and type of array, we can use **numpy.ones() method of NumPy library in Python.

Python `

import numpy as np

array = np.ones(5) print(array)

`

**Output:

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

2D Array of Ones

We can also create a 2D array (matrix) filled with ones by passing a tuple to the shape parameter.

Python `

import numpy as np

Create a 2D array of ones (3 rows, 4 columns)

ones_array_2d = np.ones((3, 4)) print(ones_array_2d)

`

Output

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

Array with a Specific Data Type

We can specify the data type of the array using the dtype parameter.

Python `

import numpy as np

Create an integer array of ones with 4 elements

ones_int_array = np.ones(4, dtype=int) print(ones_int_array)

`

**Explanation:

Multi-Dimensional Array of Ones

We can also create a higher-dimensional array (3D or more) by passing a tuple representing the shape.

Python `

import numpy as np

Create a 3D array of ones with shape (2, 3, 4)

ones_array_3d = np.ones((2, 3, 4)) print(ones_array_3d)

`

Output

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

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