Simd
Simd

Reputation: 21343

How to convert all numbers in a 2d numpy array to strings?

I have a 2d numpy array of ints called M. I would like to convert all the ints to strings returning a 2d numpy array of the same shape. How can you do that?

I tried map(str, M) but that doesn't work as it converts the individual rows into strings.

Upvotes: 0

Views: 128

Answers (2)

Janska
Janska

Reputation: 41

If I have understood it right, you are trying to convert all integer elements in the array to a string. To do so, this should work:

np.char.mod('%d',M)

Upvotes: 1

ggaurav
ggaurav

Reputation: 1804

You can use astype to cast the array to particular type

m = np.array([[1,2,3], [4,5,6]])

m = m.astype(str)
m
array([['1', '2', '3'],
       ['4', '5', '6']], dtype='<U21')

Upvotes: 1

Related Questions