Ways how to convert numpy array to string

Let’s look at a few ways to convert a numpy array to a string. We will see how to do it in both Numpy and Python-specific ways.
Numpy array to Python string

Using array2string method

The easiest way to convert a Numpy array to a string is to use the Numpy array2string dedicated function.

import numpy as np

my_array = np.array([1, 2, 3, 4, 5, 6])
print(f"My array: {my_array}")
print(type(my_array))
my_string = np.array2string(my_array)
print(f"My string converted from array: {my_string}")
print(type(my_string))

You can see that the data type changed from ndarray to string.

See also  How to find index of max value in Numpy?

Numpy array to string

Using array_str method

Similarly, you can use Numpy array_str. The only difference is that these functions give you other possibilities. You may want to check the details.

import numpy as np

my_array = np.array([1, 2, 3, 4, 5, 6])
print(f"My array: {my_array}")
print(type(my_array))
my_string = np.array_str(my_array)
print(f"My string converted from array: {my_string}")
print(type(my_string))

You can see that the data result is the same and the type changed from ndarray to string as well.

See also  How to convert numpy to xyz file?

Numpy array to string

Using Python conversion

For those who prefer to use their own Python code, you may use an easy Python conversion like that.

import numpy as np

my_array = np.array([1, 2, 3, 4, 5, 6])
print(f"My array: {my_array}")
print(type(my_array))
my_array = np.array([1, 2, 3, 4, 5, 6])
my_string = ','.join(str(x) for x in my_array)
print(f"My string converted from array: {my_string}")
print(type(my_string))

Thanks to this simple loop, string elements are printed one by one.

See also  How to stack arrays in Numpy?

Numpy array to Python string