NumPy | full_like method
Start your free 7-days trial now!
Numpy's full_like(~) method creates a Numpy array from an existing array, and fills it with the desired value. This is similar to the other Numpy _like methods such as zeros_like(~) and full_empty(~).
Parameters
1. a | array-like
Source array that will be used to construct the Numpy array. By default, the Numpy array will adopt the data type of the values as well as the size of the source array.
2. fill_value | number
The values to fill the Numpy array.
3. dtypelink | string or type | optional
The desired data type for the Numpy array. By default, the data-type would be the same as that of the source array.
Return value
A Numpy array filled with the desired value, with the same shape and type as the source array.
Examples
Using Numpy arrays
x = np.array([3,4,5])np.full_like(x, 7)
array([7, 7, 7])
Using Python arrays
x = [1,2,3]np.full_like(x, 4)
array([4., 4., 4.])
Filling a value with a type different than that of the source array
Suppose you wanted to create a Numpy array using a float, like 2.5. You might run into the following trap:
x = np.array([3,4,5])np.full_like(x, 2.5)
array([2, 2, 2])
Even when we specified a fill_value of 2.5, our Numpy array is filled with an int of value 2 instead. This happens because the original Numpy array (i.e. x in this case) is of type int, and so automatically, the full_like method assumes that you want to use int for your new Numpy array.
The solution is to specify the dtype parameter, like follows:
x = np.array([3,4,5])np.full_like(x, 2.5, dtype=float)
array([2.5, 2.5, 2.5])
Specifying type
x = [1,2,3]np.full_like(x, 4, dtype="float")
array([4., 4., 4.])
Notice how the values in the output Numpy array are 4. instead of just 4 - this means that the values are floats.
Two-dimensional arrays
x = [[1,2], [3,4]]np.full_like(x, 5)
array([[5, 5], [5, 5]])