Introduction
Every value in Python has a data type. NumPy also uses data types to determine how values are stored and processed in an array.
In this chapter, we will learn about Python and NumPy data types, how to check an array’s data type, and how to define or convert data types.
1. Data Types in Python
Python supports different data types to store different kinds of values.
Some commonly used Python data types are:
| Data Type | Description | Example |
|---|---|---|
int | Whole numbers | 100 |
float | Decimal numbers | 25.50 |
str | Text values | "Python" |
bool | True or False | True |
complex | Complex numbers | 5+3j |
Example:
age = 25
salary = 25000.50
name = "Rahul"
status = True
number = 5 + 3j
print(type(age))
print(type(salary))
print(type(name))
print(type(status))
print(type(number))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'complex'>
Here, the type() function identifies the data type of each Python variable.
2. Data Types in NumPy
NumPy supports different data types to store and handle various kinds of values in an array. Each data type represents a specific type of data:
i– Integer: Stores whole numbers without decimal values, such as 10, 25, and -50.b– Boolean: Stores logical values, such asTrueandFalse.u– Unsigned Integer: Stores only non-negative whole numbers (zero and positive integers).f– Float: Stores decimal numbers, such as 10.5, 25.75, and 3.14.c– Complex Float: Stores complex numbers containing real and imaginary parts, such as 3+4j.m– Timedelta: Stores time intervals or differences between dates and times.M– Datetime: Stores date and time values, such as 2026-11-23.O– Object: Stores references to Python objects, allowing different types of Python objects in an array.S– Byte String: Stores fixed-length sequences of bytes, commonly used for byte-based text data.U– Unicode String: Stores Unicode text, supporting characters from different languages and writing systems.V– Void: Stores fixed-size blocks of raw memory that can represent structured or custom data.
Note: These are NumPy’s data type character codes. You can use the dtype attribute to check an array’s data type.
NumPy supports several data types for storing array elements. These data types help manage memory and perform numerical calculations efficiently.
Some commonly used NumPy data types are:
| NumPy Data Type | Description |
|---|---|
int8 | 8-bit integer |
int16 | 16-bit integer |
int32 | 32-bit integer |
int64 | 64-bit integer |
float32 | 32-bit decimal number |
float64 | 64-bit decimal number |
bool | Boolean values |
complex64 | 64-bit complex number |
complex128 | 128-bit complex number |
str_ | String values |
NumPy also provides unsigned integer types such as uint8, uint16, uint32 and uint64, which store non-negative integers.
3. Checking the Data Type of an Array
The dtype attribute is used to check the data type of elements stored in a NumPy array.
Example:
import numpy as np
numbers = np.array([10, 20, 30, 40])
print(numbers.dtype)
Output (may vary by platform):
int64
Here, NumPy identifies the array elements as integers.
Let’s check another example containing decimal values.
prices = np.array([100.50, 200.75, 300.25])
print(prices.dtype)
Output:
float64
4. Creating Arrays With a Defined Data Type
By default, NumPy automatically selects a suitable data type. However, we can define the data type ourselves using the dtype parameter inside np.array().
Syntax:
np.array(values, dtype=data_type)
Example 1: Creating an Integer Array
import numpy as np
numbers = np.array([10, 20, 30], dtype="int32")
print(numbers)
print(numbers.dtype)
Output:
[10 20 30]
int32
Example 2: Create an array with data type string:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
Output:
[b'1' b'3' b'4' b'5' b'7' b'8']
|S1
Example 3: Creating a String Array
names = np.array([101, 102, 103], dtype="str")
print(names)
print(names.dtype)
Output:
['101' '102' '103']
<U3
Here, integer values are converted into strings.
5. What if a Value Cannot Be Converted?
Sometimes, a value cannot be converted into the data type specified in dtype. In such cases, NumPy raises an error.
For example, text containing alphabetic characters cannot be directly converted into an integer.
Example:
import numpy as np
numbers = np.array([10, 20, "Python"], dtype="int32")
print(numbers)
Output:
ValueError: invalid literal for int() with base 10: 'Python'
Here, NumPy cannot convert "Python" into an integer, so it raises a ValueError.
Another Example:
numbers = np.array(["10", "20", "30"], dtype="int32")
print(numbers)
Output:
[10 20 30]
Here, numeric text values can be converted into integers successfully.
6. Converting Data Type on Existing Arrays
Sometimes, we need to change the data type of an array after creating it.
NumPy provides the astype() method to convert an existing array into another data type.
Syntax:
array.astype(new_data_type)
Example 1: Converting Integer to Float
import numpy as np
numbers = np.array([10, 20, 30, 40])
new_numbers = numbers.astype("float64")
print(new_numbers)
print(new_numbers.dtype)
Output:
[10. 20. 30. 40.]
float64
Example 2: Converting Float to Integer
prices = np.array([10.5, 20.8, 30.9])
new_prices = prices.astype("int32")
print(new_prices)
print(new_prices.dtype)
Output:
[10 20 30]
int32
Here, decimal portions are removed during conversion. The values are not rounded.
Example 3: Converting Integer to String
numbers = np.array([100, 200, 300])
new_numbers = numbers.astype("str")
print(new_numbers)
print(new_numbers.dtype)
Output:
['100' '200' '300']
<U3
Here, integer values are converted into strings.
Student Task: Practice NumPy Data Types
Complete the following activities using NumPy:
Task 1: Identify Python Data Types
Create variables containing an integer, float, string and Boolean value. Use type() to identify their data types.
Task 2: Check NumPy Data Types
Create these arrays and check their data types using dtype.
numbers = np.array([10, 20, 30])
prices = np.array([99.50, 149.75, 250.25])
names = np.array(["Amit", "Rahul", "Priya"])
Task 3: Define Data Types
Create the following arrays using the dtype parameter:
- An integer array using
int32. - A decimal array using
float32. - A string array using
str.
Task 4: Handle Conversion Errors
Try converting the following array into an integer array. Observe the error.
data = np.array(["10", "20", "Python"])
Task 5: Convert Existing Arrays
Use astype() to perform these conversions:
- Integer to float.
- Float to integer.
- Integer to string.
Final Student Challenge: Manage Employee Records
A company stores employee IDs, salaries and attendance information.
Create the following arrays:
import numpy as np
employee_ids = np.array([101, 102, 103, 104])
salaries = np.array([25000.50, 30000.75, 45000.25, 50000.00])
attendance = np.array([True, False, True, True])
Complete these tasks:
- Check the data type of all three arrays.
- Convert employee IDs into
float64. - Convert salaries into
int32. - Convert employee IDs into strings.
- Print the converted arrays and their data types.
Key Takeaways
- Python provides data types such as
int,float,strandbool. - NumPy supports different numerical and non-numerical data types.
dtypechecks the data type of an array.(NumPy Float)- The
dtypeparameter defines the data type while creating an array. - Invalid conversions can raise a
ValueError. astype()converts an existing array into another data type.
Frequently Asked Questions (FAQs)
1. What are NumPy Data Types in Python?
NumPy Data Types define the type of values stored in a NumPy Array, such as integers, floating-point numbers, Boolean values, and strings.
2. What are the different data types in NumPy?
NumPy supports several data types, including int, float, bool, complex, str, and unsigned integers. Each data type is used to store a specific kind of value.
3. How do you check the NumPy Data Type of an Array?
You can use the dtype attribute to check the data type of elements stored in a NumPy Array.
Example: arr.dtype
4. What is NumPy Integer?
NumPy Integer is a data type used to store whole numbers without decimal values. Common integer types include int8, int16, int32, and int64.
5. What is NumPy Float?
NumPy Float is a data type used to store decimal numbers. Common floating-point types include float16, float32, and float64.
6. How do you create a NumPy Array with a specific data type?
You can use the dtype parameter in NumPy array creation to specify the required data type.
Example: np.array([10, 20, 30], dtype='float64')
7. How do you change the data type of an existing NumPy Array?
You can use the astype() method to convert an existing NumPy Array into another data type.
Example: arr.astype(float)
8. What happens if a value cannot be converted into a specified NumPy Data Type?
If a value cannot be converted into the specified data type, NumPy generally raises a ValueError or TypeError, depending on the conversion and input.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
