How to convert type of items in Numpy array

You may sometimes receive a Numpy array from external sources where the data type of the items are string or some other non-numeral format. Converting the data type of a Numpy array can be done using the astype method. This method on the array creates a copy of the array where every item has been converted to the destination type.

For example, assume smat is a Numpy array of strings that contain floats. To convert it to Numpy array of floats:

>>> smat
[[ '1.2', '3.4', '5.6']
 [ '7.8', '8.9', '9.0']]
>>> fmat = smat.astype(numpy.float)
>>> fmat
[[ 1.2 3.4 5.6 ]
 [ 7.8 8.9 9.0 ]]

Tried with: Python 2.7.6

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s