Exploring numpy.ones Function in Python | np.ones

While doing some project which needs mathematical operations and calculations we use numpy library. In numpy, we have NumPy arrays which facilitate advanced mathematical and other types of operations on large numbers of data. Sometimes we need our arrays to be filled with only ones that’s when the numpy.ones come into play.

Inshort numpy.ones function returns a new numpy array filled with all ones.

Need of numpy.ones

Most of you came to this article to know how to use numpy.ones in python. So, I guess you all know pretty much about mathematics as numpy is mostly about mathematical operations on large data. We often need to fill our matrix with all ones during the matrix operation in mathematics. To achieve it in python programming without tens of code lines, we have a special function present in the numpy library. This function will help us accomplish our goal by creating an identity matrix in just two lines. That function is numpy.ones().

Now I think you might know the importance of numpy.ones() function. Let’s see how we can use and implement it in our projects.

Syntax of np.ones

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

Parameters

ParameterMandatory/OptionalDescription
shapemandatoryThe shape of the new array ex. (3, 2)
dtypeoptionalThe data type of the array by default it’s float
orderoptionalIt gives us the freedom to stock the multi-dimensional array in row-major (C-style) or column-major (Fortran-style) order in memory. By default, it’s C (row-wise).
likeoptionalExperimental feature pending acceptance of NEP 35.

Return

out: ndarray

numpy.ones() function returns the array of ones with the provided shape, dtype, and order.

Let’s see the working of numpy.ones() function through some quality examples.

Example 1: Creating a One-Dimensional Array with numpy.ones

import numpy as np

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

Output:

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

Explanation:

In the above example, we have created a 1-d array with all ones in it. The example is pretty straightforward. First, we have imported the numpy array as np. After that, we have directly used the np.ones() function to create an array and passed parameter ‘5’ to the function. So we will get an array that has 5 elements in it and all are 1.

Note: The elements are having the default data type as the float. That’s why we get 1. in the array.

Example 2: Creating a Two-Dimensional Array with np.ones

import numpy as np

two_d = np.ones((3, 5))
print(two_d)

Output:

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

Explanation:

In example 2, we have created a 2D array with all ones with numpy.ones function. This example is quite similar to the first example we have seen. The only difference here is the shape of the array, as we need to create a 2D array with all ones in it. So we have positioned the parameter of np.ones as ‘(3, 5)’. Here the number of rows will be 3, and the number of columns will be 5.

Example 2: Creating a Three-Dimensional (3D) Array with np.ones

import numpy as np

three_d = np.ones((3, 5, 7))
print(three_d)

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

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

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

Explanation:

We can also create a 3D array with all ones using the np.ones() function in Python. The steps are quite similar to the first two examples. The only difference is in the shape parameter of the ones() function. Here in the shape argument, we have placed three values because we need to construct a 3D array with all ones in it.

Here also we have not declared the d-type parameter. So by default we will get the float value in our result.

Composing an Array with Different Data Types Using numpy.ones() method

In this section of the tutorial, we will perceive, how we can create arrays consisting of all ones having different data types. The d-type or data type of the numpy.ones method can be int, float, string, etc. So, without wasting any further time let’s directly jump to the examples.

1. Creating an Array where Data Type is integer Using np.ones()

import numpy as np

array_int = np.ones((3, 5), dtype=int)
print(array_int)

Output:

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

Explanation:

We have created all one’s numpy array with data type as an integer in the above example. The example is pretty straightforward. But for beginners, let me briefly explain it. Here, we have imported the numpy array as np.one() function is available in the numpy library. We already have seen the working of numpy.ones() the only extra thing we have done here is by adding the d-type parameter. We have made the data type integer. Hence, you can see the example’s output, which is of type integer, not float.

2. Creating an Array where Data Type is string Using numpy.ones()

import numpy as np

array_str = np.ones((3, 5), dtype=str)
print(array_str)

Output:

[['1' '1' '1' '1' '1']
 ['1' '1' '1' '1' '1']
 ['1' '1' '1' '1' '1']]

Explanation:

So, in this case we have generated a 2d numpy array filled with all ones and the data type of the arrays is string.
This example is identical to the previous example. Here the only change is instead of integer we have have used ‘str’ as the argument in the function. Hence we will get a numpy array with string data type.

3. Composing an Array with mixed Data Type in the form of Tuples Using numpy.ones()

import numpy as np

array_tuple = np.ones((3, 5), dtype=[('x', 'int'), ('y', 'float')])
print(array_tuple)

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.) (1, 1.) (1, 1.) (1, 1.)]]

Explanation:

We can specify the array elements as a tuple and specify their data types too.

Working with order Parameter of numpy.ones Function

import numpy as np
import time

dimension = [2000, 2000]

cstyle = np.ones(dimension, order="C")
fortranstyle = np.ones(dimension, order="F")

print("We're performing an column operation on both the arrays to check the performance.")

start = time.time()
np.cumsum(cstyle, axis=1)
print("Time taken to perform column operation on C-style - ", time.time()-start)

start = time.time()
np.cumsum(fortranstyle, axis=1)
print("Time taken to perform column operation on Fortran-style - ", time.time()-start)

print("\nWe're performing an row operation on both the arrays to check the performance.")

start = time.time()
np.cumsum(cstyle, axis=0)
print("Time taken to perform row operation on C-style - ", time.time()-start)

start = time.time()
np.cumsum(fortranstyle, axis=0)
print("Time taken to perform row operation on Fortran-style - ", time.time()-start)

Output:

We're performing an column operation on both the arrays to check the performance.
Time taken to perform column operation on C-style -  0.07280611991882324
Time taken to perform column operation on Fortran-style -  
0.028921842575073242

We're performing an row operation on both the arrays to check the performance.
Time taken to perform row operation on C-style -  0.026929855346679688
Time taken to perform row operation on Fortran-style -  0.0718083381652832

Explanation:

As there is no elemental difference between the C type and Fortran type, we need to use operations to check the difference. In this case, we’ll use np.cumsum() to calculate the sum by row operations and by column operations. Then we’ll check the operations on both the array types and deduce a conclusion.

We’ve first declared two numpy ones array by using different order parameters. Then we’ll use the time.time() python timer class to get the time taken in each operation. time.time() – start will give us the exact amount of time taken by the row/column operation in np.cumsum().

From the output, we can check that the column operations are faster on the Fortran type array and row operations are faster in the C type. Similarly, we can use this order parameter to make our calculations faster if we know the operations beforehand.

Numpy.ones Vs. Numpy.ones_like

Numpy.onesNumpy.ones_like
Syntaxnumpy.ones(shapedtype=Noneorder=’C’)numpy.ones_like(adtype=Noneorder=’K’subok=Trueshape=None)
ReturnsReturn a new array of given shape and type, filled with ones.Return an array of ones with the same shape and type as a given array.
Exampleimport numpy as np
print(np.ones([3,4],dtype=int))
import numpy as np
two_d=np.random.rand(4,5)
print(two_d)
print(np.ones_like(two_d,int))
Output[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[0.04153551 0.65643199 0.32287169 0.60656863 0.52434272]
[0.58110881 0.47309099 0.38251042 0.86157837 0.22099276]
[0.60140397 0.62901982 0.51812488 0.0887905 0.78431815]
[0.85056633 0.93509825 0.20018143 0.06351918 0.40621227]]
[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]

Summary:

In this article, we learned how to create a 1D, 2D, and 3D numpy array of given shapes and filled with ones. We have also seen how we can play around with various data types in numpy.ones function and choose the best according to our need. Following that we learned how we can work with the underrated and typical parameter ‘order’. At last, we possess the Difference between the np.ones and numpy.ones_like.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments