Skip to content
Home » numpy Part 10 – Data Type Objects in numpy

numpy Part 10 – Data Type Objects in numpy

Spread the love

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply