Open In App
Related Articles

NumPy | Create array filled with all ones

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

Example:

Python3

import numpy as np
  
array = np.ones(5)
print(array)

                    

Output:

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

Syntax

Syntax: np.ones(shape, dtype=None, order=’C’, *, like=None)

Parameters:

  • shape : integer or sequence of integers
  • order :
    • C_contiguous or F_contiguous
    • C-contiguous order in memory(last index varies the fastest)
    • C order means that operating row-rise on the array will be slightly quicker
    • FORTRAN-contiguous order in memory (first index varies the fastest).
    • F order means that column-wise operations will be faster.
  • dtype : [optional, float(byDefault)] Data type of returned array.
  • like: [optional] allows you to create an array with the same shape and data type as another array-like object

More Examples

Let’s look at more example on how to create array with all ones with NumPy:

Example 1:

Python3

# Python Program to create array with all ones
import numpy as geek 
  
a = geek.ones(3, dtype = int
print("Matrix a : \n", a) 
  
b = geek.ones([3, 3], dtype = int
print("\nMatrix b : \n", b) 

                    

Output:  

Matrix a : 
 [1 1 1]
Matrix b : 
 [[1 1 1]
 [1 1 1]
 [1 1 1]]

Example 2: 

Python3

# Python Program to create array with all ones
import numpy as geek 
  
c = geek.ones([5, 3]) 
print("\nMatrix c : \n", c) 
  
d = geek.ones([5, 2], dtype = float
print("\nMatrix d : \n", d) 

                    

Output:  

Matrix c : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
Matrix d : 
 [[ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]
 [ 1.  1.]]


Last Updated : 09 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads