NumPy strings.isnumeric()
The numpy.strings.isnumeric()
function checks if each element in an input array consists only of numeric characters.
It returns a boolean array indicating whether each string contains only numeric characters.
Syntax
</>
Copy
numpy.strings.isnumeric(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x | array_like, with StringDType or str_ dtype | Array of strings to check for numeric characters. |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array where results are stored. If None, a new array is created. |
where | array_like, optional | Boolean mask specifying which elements to check. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior when processing the function. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Specifies the data type of the output array. |
subok | bool, optional | Determines if subclasses of ndarray are preserved in the output. |
Return Value
Returns an array of boolean values indicating whether each string consists only of numeric characters.
Examples
1. Checking If Strings Contain Only Numeric Characters
In this example, we check whether each element in a string array contains only numeric characters.
</>
Copy
import numpy as np
# Define an array of strings
string_array = np.array(["123", "abc", "⅕", "3.14", "0123"]) # Includes Unicode numeric characters
# Check if each string is numeric
result = np.strings.isnumeric(string_array)
# Print the results
print("Input Strings:", string_array)
print("Are Numeric:", result)
Output:
Input Strings: ['123' 'abc' '⅕' '3.14' '0123']
Are Numeric: [ True False True False True]

2. Using the out
Parameter
Storing the output in a predefined array instead of creating a new one.
</>
Copy
import numpy as np
# Define an array of strings
string_array = np.array(["123", "hello", "456"])
# Create an output array with the same shape
output_array = np.empty_like(string_array, dtype=bool)
# Check for numeric strings and store in output_array
np.strings.isnumeric(string_array, out=output_array)
# Print the results
print("Stored results:", output_array)
Output:
Stored results: [ True False True]

3. Using the where
Parameter
Checking numeric strings only in specific positions using a mask.
</>
Copy
import numpy as np
# Define an array of strings
string_array = np.array(["123", "45a", "⅞", "789"])
# Define a mask (check only selected elements)
mask = np.array([True, False, True, False])
# Apply the mask
result = np.strings.isnumeric(string_array, where=mask)
# Print the results
print("Checked values:", result)
Output:
Checked values: [ True False True False]

The function checks only elements where mask=True
, while other values remain unchanged.