NumPy ones()

The ones() method creates a new array of given shape and type, filled with ones.

import numpy as np

# create an array of 1s array1 = np.ones(5)
print(array1) # Output: [1. 1. 1. 1. 1.]

ones() Syntax

The syntax of ones() is:

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

ones() Arguments

The ones() method takes three arguments:

  • shape - desired new shape of the array (can be integer or tuple of integers)
  • dtype (optional) - datatype of the returned array
  • order (optional) - specifies the order in which the ones are filled

ones() Return Value

The ones() method returns the array of given shape, order, and datatype filled with 1s.


Example 1: Create Array With ones

import numpy as np

# create a float array of 1s array1 = np.ones(5
) print('Float Array: ',array1)
# create an int array of 1s array2 = np.ones(5, dtype = int)
print('Int Array: ',array2)

Output

Float Array:  [1. 1. 1. 1. 1.]
Int Array:  [1 1 1 1 1]

If unspecified, the default dtype is float.


Example 2: Create nd-Array With ones

import numpy as np

# create a n-d array of 1s array1 = np.ones([2,3])
print('n-d array:\n',array1)

Output

n-d array:
 [[1. 1. 1.]
 [1. 1. 1.]]