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

ParameterTypeDescription
xarray_like, with StringDType or str_ dtypeArray of strings to check for numeric characters.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where results are stored. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying which elements to check. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when processing the function.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalSpecifies the data type of the output array.
subokbool, optionalDetermines 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.