NumPy strings.isdigit()

The numpy.strings.isdigit() function checks whether each string element in an input array consists entirely of digits and contains at least one character. It returns True for elements that meet this condition and False otherwise.

Syntax

</>
Copy
numpy.strings.isdigit(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)

Parameters

ParameterTypeDescription
xarray_like, with StringDType, bytes_, or str_ dtypeInput array containing string elements to be checked.
outndarray, None, or tuple of ndarray and None, optionalOptional output array to store results. If None, a new array is created.
wherearray_like, optionalBoolean mask that determines which elements to check. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when applying the function.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalSpecifies the output array’s data type.
subokbool, optionalDetermines if subclasses of ndarray are preserved in the output.

Return Value

Returns an array of boolean values where True indicates that the corresponding string consists only of digit characters, and False otherwise. If the input is a scalar, a scalar boolean value is returned.


Examples

1. Checking if Strings Contain Only Digits

In this example, we check whether each string element in an array contains only digits.

</>
Copy
import numpy as np

# Define an array of strings
strings = np.array(["123", "abc", "4567", "78a", "90"])

# Check if each element contains only digits
result = np.strings.isdigit(strings)

# Print the result
print("Input strings:", strings)
print("Is digit:", result)

Output:

Input strings: ['123' 'abc' '4567' '78a' '90']
Is digit: [ True False  True False  True]

2. Using the out Parameter

Here, we use an output array to store the results instead of creating a new array.

</>
Copy
import numpy as np

# Define an array of strings
strings = np.array(["100", "test", "007", "123abc"])

# Create an output array
output_array = np.empty_like(strings, dtype=bool)

# Store results in output_array
np.strings.isdigit(strings, out=output_array)

# Print the results
print("Computed results:", output_array)

Output:

Computed results: [ True False  True False]

3. Using the where Parameter

Using a condition to check digit characters only for specific elements.

</>
Copy
import numpy as np

# Define an array of strings
strings = np.array(["42", "apple", "678", "word"])

# Define a condition (check only selected elements)
mask = np.array([True, False, True, False])

# Apply the isdigit function only where mask is True
result = np.strings.isdigit(strings, where=mask)

# Print the results
print("Results with mask:", result)

Output:

Results with mask: [ True False  True False]

The function is applied only to elements where mask=True. The other elements retain their original values.