Today we’ll be talking about data type objects in numpy.
Up to now we’ve been using dtype to determine the type of data in an array. Here’s an example:
import numpy as np
nums = [[1.1, 2.2, 3.3],
[4.4, 5.5, 6.6],
[7.7, 8.8, 9.9]]
n = np.array(nums, dtype = int)
print(n)
Here’s the output:
[[1 2 3]
[4 5 6]
[7 8 9]]
You can use dtype to define a data type and assign it to a variable. Let’s modify our code:
import numpy as np
nums = [[1.1, 2.2, 3.3],
[4.4, 5.5, 6.6],
[7.7, 8.8, 9.9]]
# Let's define a data type, like for instance int16, and assign it to the
# variable a.
a = np.dtype(np.int16)
# Now a is a data type and can be used like so:
n = np.array(nums, dtype = a)
print(n)
If you run this program, you’ll get the same output as before.
In the example above we used the int16 type, which means 16-bit integer. int16 corresponds to ‘i2’, int32 corresponds to ‘i4’, and so on. ‘i2’ means a 2-byte integer, ‘i4’ means a 4-byte integer. So, we could use this notation instead:
a = np.dtype('i2')
i1, i2, i4, etc. stand for 1-byte integers, 2-byte integers, 4-byte integers and so on. Generally, the letter i is used for integers. We use other letters for other data types, for example f for floats, b for bools, S for strings, and so on.
Here’s the video version of the article: