Understanding NumPy Data Types
Introduction
Welcome back to From Lists to Arrays! In earlier lessons, we used np.array() to turn lists into arrays and explored how arrays are structured. Today, we’ll look at another important part of an array: its shared data type, or dtype. We’ll learn how to read the dtype, see how mixed values affect it, and choose a dtype when we create an array.
Reading a dtype with .dtype
When we create an array from a list, NumPy chooses a data type for it. We can inspect that choice with the array’s .dtype attribute. Let’s start with ticket counts, which are all whole numbers. As always, we import NumPy as np first; the later snippets in this lesson continue from this setup. The code prints the dtype that NumPy inferred for counts.
The values fit the integer type NumPy chose, shown in the output as int64. This name identifies the array’s shared type: every value in counts is stored as an integer.
One Decimal Changes Everything
An array has one shared dtype, so NumPy looks for a type that can represent every value. Here, the list contains one decimal number alongside whole numbers. We print the resulting array and its dtype to see how NumPy handles the mix.
NumPy selects float64, allowing the array to hold the decimal value. The whole-number values are represented as floats, too, which is why they appear with decimal points.
One String Turns All Values into Text
Python lists can hold values of different types together. NumPy arrays, however, use one shared dtype. We’ll print the original list, then convert it to an array and print the array and its dtype. This makes the difference between the two containers visible.
The list keeps its integer, string, and float values. To give the array one type that can represent them all, NumPy converts the values to text. The dtype <U32 indicates Unicode text storage.
