NumPy Data Types
Learn how NumPy stores numbers, text, Boolean values, and other kinds of data in arrays. Understand the dtype attribute, common NumPy data types, explicit type selection, and type conversion.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand what a data type means in NumPy.
- Identify common NumPy integer and floating-point types.
- Work with Boolean and string arrays.
- Inspect an array's data type using the dtype attribute.
- Specify a data type while creating an array.
- Convert array elements using the astype() method.
- Understand type conversion and possible data loss.
- Choose suitable data types for numerical calculations.
- Identify common data type errors.
- Apply data type concepts to practical datasets.
array.dtype.
2. What Are NumPy Data Types?
A data type describes the kind of value stored in an array. For example, an array may contain integers, decimal numbers, Boolean values, or text.
NumPy arrays generally store elements using a common data type. This helps NumPy manage memory efficiently and perform numerical operations consistently.
Example: Creating Arrays with Different Data
Example Output
The exact integer type can depend on the platform and the values used. NumPy uses a Unicode string type for the string array in this example.
| Array | Example Values | Typical dtype |
|---|---|---|
| Integer array | [10, 20, 30] |
int64 or another integer type |
| Floating-point array | [10.5, 20.5] |
float64 |
| Boolean array | [True, False] |
bool |
| String array | ["Red", "Blue"] |
Unicode string type |
3. Understanding the dtype Attribute
The dtype attribute tells you which data type NumPy
uses to represent the elements of an array. It is useful when
checking numerical precision, understanding conversions, and
troubleshooting calculations.
Inspecting Array Data Types
| Expression | Purpose |
|---|---|
values.dtype |
Returns the data type of the array elements. |
values.shape |
Returns the dimensions of the array. |
values.size |
Returns the total number of elements. |
values.ndim |
Returns the number of array dimensions. |
dtype is an attribute,
so write values.dtype, not
values.dtype().
4. Integer Data Types
Integer data types store whole numbers without fractional parts. NumPy provides signed and unsigned integer types with different storage sizes.
int8anduint8int16anduint16int32anduint32int64anduint64
Signed integers can represent negative and positive values. Unsigned integers represent non-negative values and provide a different range for the same number of bits.
Integer Type Comparison
| Data Type | Storage | Typical Use |
|---|---|---|
int8 |
8 bits | Small signed integer values. |
int16 |
16 bits | Integer data requiring a larger range than int8. |
int32 |
32 bits | General-purpose fixed-width integer data. |
int64 |
64 bits | Integer values requiring a wider range. |
uint8 |
8 bits | Non-negative values such as many image pixel values. |
5. Floating-Point Data Types
Floating-point types represent numbers that may contain fractional parts. They are commonly used for measurements, averages, prices, percentages, and scientific calculations.
float16uses 16 bits.float32uses 32 bits.float64uses 64 bits.
Comparing Floating-Point Types
| Type | Storage | Consideration |
|---|---|---|
float16 |
16 bits | Uses less memory but has limited precision and range. |
float32 |
32 bits | Often useful when balancing memory and precision. |
float64 |
64 bits | Provides greater precision than float32 in typical calculations. |
6. Boolean and String Data Types
Boolean Data Type
The Boolean data type, represented by bool, stores
logical values: True and False.
Boolean arrays are especially useful for filtering data.
String Data Type
NumPy supports arrays containing text. When strings are created
using np.array(), NumPy commonly infers a fixed-width
Unicode or byte-string data type.
7. Specifying a Data Type During Array Creation
You can specify the desired data type using the
dtype parameter of np.array().
This helps control how values are represented in the array.
Example Output
When integers are converted to floating-point values, the output can display decimal points. When values are converted to Boolean, zero becomes False and nonzero numeric values become True.
np.int32, np.float64, and
np.bool_ when you need an explicit data type.
8. Converting Data Types with astype()
The astype() method creates a new array with elements
converted to the requested data type. It is commonly used to
convert integers to floating-point values or floating-point
values to integers.
Converting Floating-Point Values to Integers
When converting finite floating-point values to integer types, the fractional part is discarded rather than rounded to the nearest integer.
Converting Numbers to Strings
9. Understanding Type Promotion
When arrays or values with different data types are combined, NumPy may choose a common data type that can represent the resulting values. This behavior is known as type promotion.
Example Output
In this example, the result uses a floating-point type so that the decimal values can be represented in the calculation. The exact promoted type depends on the input dtypes and operation.
dtype when combining values with different types,
especially in scientific calculations and data processing.
10. Data Type and Memory Usage
A NumPy array's itemsize attribute reports the
number of bytes used by each element. Choosing an appropriate
dtype can reduce memory usage when the required range and
precision are understood.
Understanding the Output
Each int16 element uses 2 bytes, while each int64 element uses
8 bytes. The nbytes attribute reports the total
memory occupied by the array's element data, excluding other
array-object overhead.
| Attribute | Meaning |
|---|---|
dtype |
Data type used for array elements. |
itemsize |
Size in bytes of one array element. |
nbytes |
Total bytes occupied by the array's element data. |
size |
Total number of array elements. |
11. Common Data Type Errors
| Problem | Reason | Solution |
|---|---|---|
| Unexpected decimal values | NumPy inferred a floating-point type. | Inspect dtype and specify a type if needed. |
| Lost fractional parts | Floating-point values were converted to integers. | Keep a floating-point type when decimals are required. |
| Integer range problems | The selected integer type cannot represent a value. | Choose a type with a suitable range. |
| Unexpected Boolean values | Nonzero numeric values convert to True. | Check the conversion rules and source values. |
| String truncation | A fixed-width string dtype has insufficient capacity. | Choose an appropriate string representation before assignment. |
| Unexpected calculation results | Precision or type promotion affects the result. | Inspect the input and output dtypes. |
dtype, shape, and sample values
before changing its data type.
12. Practical Activity: Student Marks Analysis
Activity: Inspect and Convert Marks
Samadhan is preparing student marks for analysis. Use NumPy data types to inspect integer values, convert marks to floating-point values, calculate the average, and check memory usage.
Expected Output
The activity demonstrates how to inspect an array's data type, convert integer marks to floating-point values, calculate an average, and examine the memory used by array elements.
13. Practice Exercises
Use the following arrays to complete the exercises:
- Print the data type of each array.
- Create an integer array using
np.int16. - Create a floating-point array using
np.float32. - Convert the values array to floating-point values using
astype(). - Convert the prices array to integers and observe what happens to the fractional parts.
- Print the item size of the values array.
- Print the total element-data bytes using
nbytes. - Create a string array containing three names and inspect its dtype.
Challenge Exercise
Pradnya is preparing a small sales dataset. Create a NumPy array containing sales values and complete the following tasks:
- Create an integer array and inspect its dtype.
- Convert the array to float32.
- Calculate the average sales value.
- Compare the item sizes of int32 and float64 arrays.
- Explain why converting decimal sales values to integers may lose information.
- Choose an appropriate data type for storing whole-number quantities.
Summary
In this lesson, we learned that NumPy data types define how array
elements are represented. We explored integer, floating-point,
Boolean, and string data types and used the dtype
attribute to inspect them.
We learned how to specify a data type during array creation and
how to convert values using astype(). We also
explored type promotion, memory usage, and the risks of losing
information during conversion.
Choosing the correct data type helps maintain numerical accuracy,
manage memory, and avoid unexpected results in array operations.
Practice inspecting and converting arrays to become more confident
with NumPy data types.