Create a Numpy array filled with all ones

In this article, we will learn how to create a Numpy array filled with all one, given the shape and type of array.

We can use Numpy.ones() method to do this task. This method takes three parameters, discussed below –

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(byDeafult)] Data type of returned array.  

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


Output:

Matrix a : 
 [1 1 1]

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

 
Code #2:



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


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.]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.