np.full_like: What is Numpy full_like() Function

The np.full_like() is defined under the numpy library, which can be imported as import numpy as np, and we can create multidimensional arrays.

Numpy full_like()

The np.full_like() is a numpy library function that returns the new array with the same shape and type as a given array. The full_like() function contains four parameters and returns an array of the similar shape and size as the given array. 

Syntax

numpy.full_like(shape, order, dtype, subok ) 

Parameters

It takes 4 parameters, out of which 2 parameters are optional. 

The first parameter is the shape, which represents the number of rows.

The second parameter is the order, representing its order in the memory. (C_contiguous or F_contiguous).

The third parameter is the dtype(datatype) of the returned array. It is optional and has a float value by default.

The fourth parameter is a bool parameter subok, which checks if we have to create a sub-class of the main array or not.

Return Value

It returns a ndarray of the same shape and size.

Programs on full_like() method in Python

Write a program to show the working of the full_like() function in Python.

# app.py

import numpy as np

arr = np.arange(15, dtype=int).reshape(3, 5)
print("arr before full_like : \n", arr)

print("\narr after full_like : \n", np.full_like(arr, 15.0))

Output

python3 app.py
arr before full_like :
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

arr after full_like :
 [[15 15 15 15 15]
 [15 15 15 15 15]
 [15 15 15 15 15]]

In this example, we can see that using full_like(), we have preserved arrays’ shape and size and returned a new array with the new value.

Write a program to take a 4×4 matrix and then apply the full_like() function that also passes -3 as the input for the new array.

# app.py

import numpy as np

arr2 = np.arange(16, dtype=float).reshape(4, 4)
print("\n\narr2 before full_like : \n", arr2)

# using full_like
print("\narr2 after full_like : \n", np.full_like(arr2, -3))

Output

python3 app.py

arr2 before full_like :
 [[ 0.  1.  2.  3.]
 [ 4.  5.  6.  7.]
 [ 8.  9. 10. 11.]
 [12. 13. 14. 15.]]

arr2 after full_like :
 [[-3. -3. -3. -3.]
 [-3. -3. -3. -3.]
 [-3. -3. -3. -3.]
 [-3. -3. -3. -3.]]

In this example, we can see that we have passed a 4×4 array, and the value in the new array is negative, which is -3 hence showing the attributes of full_like().

See also

Numpy bmat()

Numpy asmatrix()

Numpy diag_indices()

Numpy diag()

Numpy diagflat()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.