Skip to main content

12.4) Controlling The Data Type


All elements of an array need to be the same data type. If you have mixed types in your list, this function will try to convert all elements to the same type. We call this upcasting. Integers are converted to floats and numbers to strings, so that all the elements are the same type. For example:

>>> print np.array([1,2,3,4.0,5,6])   # integers are converted to floats
[ 1.  2.  3.  4.  5.  6.]
>>> print np.array([1,2,3,'4',5,6])   # numbers are converted to strings
['1' '2' '3' '4' '5' '6']

To control the type of data in your array, use the dtype option (you can search online to find a description of all the possible options):

>>> print np.array([1,2,3,'4',5,6],dtype='i')  # i is for integer
[1 2 3 4 5 6]
>>> print np.array([1,2,3,'4',5,6],dtype='d')  # d for double precision float
[ 1.  2.  3.  4.  5.  6.]

The default type when creating an array is double precision float (d).

If it’s not possible to convert all the elements to the type requested, you will get an error:,/p>

>>> print np.array([1,2,3,'four',5,6],dtype='d')
Traceback (most recent call last):
  File "<pyshell#60>", line 1, in <module>
    print np.array([1,2,3,'four',5,6],dtype='d')
ValueError: could not convert string to float: four

Convert a list of all the integers from 1 to 10 to an array of floats.