What is the numpy.array_str() function in Python?
Overview
The array_str() function in Python is used to return a string representation of the data in an array passed to it.
Syntax
numpy.array_str(a, precision=None, suppress_small=None)
Parameters
The array_str() function takes the following parameter values:
a: This represents the input array.precision: This represents the floating point precision. This is optional.suppress_small: This represents the numbers “very close” to zero as zero. It takes a Boolean value, and by default, the value isFalse. This is optional.
Return value
The array_str() function returns the string representation of the data in an array.
Example
import numpy as np# creating an arraymyarray = np.array([1, 2, 3, 4, 5])# implementing the array_str() functionstringrep = np.array_str(myarray, precision = 6, suppress_small = True)# printing the string representationprint(stringrep)print(type(stringrep))
Explanation
- Line 1: We import the
numpymodule. - Line 4: We create an array
myarrayusing thearray()function. - Line 7: We implement the
array_str()method on the given array using a precision of6and asuppress_smallvalue asTrue. The output is assigned to a new variablestringrep. - Line 11: We print the array
stringrep. - Line 12: Using the
type()function, we obtain the data type of the arraystringrepand print it.