I have a 2D numpy array and I want to change its rows into strings so that I'll have an 1D numpy array where each element corresponds to a string corresponding to a row of the 2D array. I feel like there should be an easy way to do this but I cannot find it.
3 Answers
I believe you are looking for the following.
import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(x.shape) # prints (3,3)
y = []
for row in x:
item = ''
for column in row:
item = item + str(column)
y.append(item)
y = np.array(y)
print(y.shape) # prints (3,)
print(y) # prints ['123' '456' '789']
print(y[1][1]) # prints 5
Comments
Numpy array is made to work with numbers. I would discourage its usage with strings or any other object, unless you really know what you are doing. Having said that,
>>> import numpy as np
>>> A = np.arange(9).reshape(3,3)
>>> R = [np.array_str(a) for a in A]
>>> print R
['[ 0. 1. 2.]', '[ 3. 4. 5.]', '[ 6. 7. 8.]']
R there is a standar python list, which probably would suffice for most usages. If you really really want a numpy array, and you know what you are doing with it, you can just wrap the list:
>>> R = np.asarray(R, dtype=str)
Note that you could have also used the solution from @JoséSánchez, but np.array_str gives you much more flexibility to how you store rows as strings than calling str. E.g. you can set precission to X decimals or round small numbers to 0.