NumPy ndarray.fill()
The numpy.ndarray.fill()
method fills an entire NumPy array with a specified scalar value. This is an in-place operation, meaning it modifies the existing array rather than creating a new one.
Syntax
ndarray.fill(value)
Parameters
Parameter | Type | Description |
---|---|---|
value | scalar | The scalar value used to fill the array. |
Return Value
The method does not return a new array but modifies the existing array in place by filling it with the given value.
Examples
1. Filling an Array with a Single Value
In this example, we create an empty NumPy array and use fill()
to populate it with a constant value.
import numpy as np
# Create an array of shape (3, 3) with uninitialized values
arr = np.empty((3, 3))
# Fill the entire array with the value 7
arr.fill(7)
# Print the modified array
print(arr)
Output:
[[7. 7. 7.]
[7. 7. 7.]
[7. 7. 7.]]
The fill()
method replaces all elements in the array with the value 7
, modifying it in place.
2. Using fill()
with Floating-Point Values
We can also use fill()
with floating-point numbers.
import numpy as np
# Create an array of shape (2, 4) with uninitialized values
arr = np.empty((2, 4))
# Fill the array with the value 3.14 (Pi approximation)
arr.fill(3.14)
# Print the modified array
print(arr)
Output:
[[3.14 3.14 3.14 3.14]
[3.14 3.14 3.14 3.14]]
The method works the same way regardless of whether the value is an integer or a floating-point number.
3. Filling an Integer Array
If the array has an integer data type, fill()
will round floating-point values before storing them.
import numpy as np
# Create an integer array of shape (2, 2)
arr = np.empty((2, 2), dtype=int)
# Fill the array with the value 5.9 (which will be converted to 5)
arr.fill(5.9)
# Print the modified array
print(arr)
Output:
[[5 5]
[5 5]]
Since the array has an integer data type, the floating-point value 5.9
is truncated to 5
.
4. Filling a Boolean Array
The fill()
method can also be used with boolean arrays.
import numpy as np
# Create a boolean array of shape (3, 2)
arr = np.empty((3, 2), dtype=bool)
# Fill the array with True
arr.fill(True)
# Print the modified array
print(arr)
Output:
[[ True True]
[ True True]
[ True True]]
For boolean arrays, fill()
will assign True
or False
based on the given value.