w3resource

NumPy String: numpy.char.mod() function

numpy.char.mod() function

numpy.char.mod() is used to apply string formatting to arrays of strings element-wise. It is similar to the % operator used for string formatting in Python, but operates on NumPy arrays instead of individual strings.

This function is useful in -

  • Formatting text data in arrays: You can use numpy.char.mod() to format text data stored in NumPy arrays for further processing or analysis. This can be useful when you need to format data for output, such as generating reports, tables, or other structured text.
  • Creating labels or annotations: You can use numpy.char.mod() to create labels or annotations for data visualizations, where you need to combine numerical and textual data in a consistent format across multiple elements.

Syntax:

numpy.char.mod(a, values)

Parameters:

Name Description Required /
Optional
a: array_like of str or unicode Input array. Required
values: array_like of ints These values will be element-wise interpolated into the string. Required

Return value:

out : ndarray - Output array of str or unicode, depending on input types.

Example: Converting integer arrays to string arrays using NumPy's char.mod()

import numpy as np  
a = np.array([0, 120, 1254872])
print("Integer arays:")
print (a) 
print("String arrays")
s = np.char.mod('%d', a)
print(s)

Output:

Integer arays:
[      0     120 1254872]
String arrays:
['0' '120' '1254872']

In the above code -
The numpy.char.mod() function is called with the format string '%d' (which represents an integer placeholder) and the integer array 'a' as arguments. This applies the integer-to-string conversion to each element of the array 'a' and returns a new string array 's'.

Previous: multiply()
Next: capitalize()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/numpy/string-operations/mod.php