Changing Array Data Types
Introduction
Welcome back to From Lists to Arrays. We’re building on our work creating arrays and describing their structure. Today, we’ll learn how to change an existing array’s data type with astype without rebuilding it from a list. By the end, we’ll be able to predict what happens when we convert decimal values to integers, integers to floats, and numbers to Booleans.
Introducing astype
An array’s data type affects how its values are represented. For example, whole-number counts may be more useful as integers, while calculations that include decimals may need floats. As you may recall from the dtype lesson, we can inspect an array’s type with .dtype. To convert an existing array, we call its astype method and pass the target type. As always, we import NumPy as np first; the later snippets continue from this setup.
Here, readings keeps its decimal values, while whole is a converted array with an integer dtype. The call uses the existing array as its starting point, so we don’t need to make a list and create a new array from scratch. Next, we’ll look at exactly how the decimal values change.
The Truncation Rule
When we convert floats to integers with astype, NumPy truncates toward zero. That means it drops the decimal part; it does not round to the nearest integer. Thus, 7.9 becomes 7, and -1.7 becomes -1. Notice that the negative value moves toward zero, too. Rounding would behave differently: -1.7 rounded to the nearest whole number is -2, not -1. Keeping this rule in mind helps us predict converted values before we run the code.
astype Returns a Copy
With our dtype changing from float64 to int64, astype creates a converted array and leaves readings unchanged. The following print statements show the original values, the converted values, and each array’s dtype. Compare the first two lines: the decimal values are still present in the original, even after conversion.
The output confirms both the conversion and the unchanged original:
The first line still contains decimals, while the second contains truncated integers. The dtype lines confirm that readings remains float64 and whole is int64. We can keep using either array for the task that suits its values.
