As we know Numpy is the most popular library in Python used in Machine learning and more. You can easily convert a Numpy array to various formats such as lists, data frames, and CSV files. In this article, we will see how you can convert Numpy array to strings in Python. 

For this purpose we are using a function called numpy.array.str() in python.

Let’s start with Syntax

numpy.array.str(array, max_line, inline, precision=None, supress_small = None )

Where,

Array = An input array.

Max_line = Default rate is 75, provides newlines if text is longer.

Precision = Default precision will be 8.

Supress_small = Represents very small numbers as 0.

1. Convert Numpy array to strings in Python

we are using numpy.array.str() function for this process and this function is very simple and does the conversion job with ease.

let’s see how it works!

#Imprts the library
import numpy as numpy

#Creates an array
test_array = np.array([1,2,3])

#Prints an array
print('Given array: ',test_array)

print(type(test_array))

#Convert to string 
out_array = numpy.array_str(test_array)

print('Numpy array to strings: ',out_array)
#Prints the array with type 
print(type(out_array))
Given array:  [1 2 3]
<class 'numpy.ndarray'>
Numpy array to strings:  [1 2 3]
<class 'str'>

In this section, we have imported the Numpy library and created an array. After that with the use of np.array_str() function, we have converted array to strings in python.

2. Converting Numpy array to Strings with parameters

In the above section, we have worked on the simple example where we have able to convert Numpy array to strings in python using the function np.array_str().

Just like that, we have mentioned some parameters in the syntax of that function. Let’s see how they work.

#Imports the library
import numpy as np

#Creates an array
arr = np.array([1,2,3,4])

#Prints an array with type
print('The array: ', arr)
print(type(arr))

#Output array, array to strings
out_arr = np.array_str(arr,precision=5,suppress_small=True)
print('The string form of array is: ',out_arr)
#Prints the array with type
print(type(out_arr))
The array:  [1 2 3 4]
<class 'numpy.ndarray'>
The string form of array is:  [1 2 3 4]
<class 'str'>

Fantastic!!! Kudos on your output. you have successfully converted array to strings using the np.array_str() function in Python. This method is very easy and quick. Try more and more examples to get better at this.

Conclusion

Numpy being a popular library for mathematical computations, it offers many functions such as np.array_str(), which assist you in converting an array to strings in python.

This article tells you all about converting Numpy arrays to different formats with an ease.

That’s all for now. Happy Learning!!!

More read: Numpy.org

Categorized in:

Tagged in:

, ,