0
0
NumPydata~5 mins

Specifying dtype during creation in NumPy

Choose your learning style9 modes available
Introduction

We use dtype to tell numpy what kind of data we want to store. This helps save memory and makes calculations faster.

When you want to store numbers as integers instead of floats to save space.
When you need to work with text data and want to specify string length.
When you want to make sure your data uses a specific format for calculations.
When you want to create arrays with boolean values for true/false checks.
When you want to avoid automatic type guessing by numpy.
Syntax
NumPy
numpy.array(data, dtype=desired_type)

data is the list or sequence of values you want to convert to an array.

dtype tells numpy the type of data, like int, float, bool, or str.

Examples
Creates an integer array with values 1, 2, 3.
NumPy
import numpy as np
arr = np.array([1, 2, 3], dtype=int)
Creates a float array with decimal numbers.
NumPy
arr = np.array([1.5, 2.5, 3.5], dtype=float)
Creates a boolean array where 1 is True and 0 is False.
NumPy
arr = np.array([1, 0, 1], dtype=bool)
Creates a string array with max length 2 characters.
NumPy
arr = np.array(['a', 'b', 'c'], dtype='U2')
Sample Program

This program shows how to create numpy arrays with different data types by specifying dtype during creation.

NumPy
import numpy as np

# Create integer array
int_arr = np.array([10, 20, 30], dtype=int)
print('Integer array:', int_arr)
print('Data type:', int_arr.dtype)

# Create float array
float_arr = np.array([1, 2, 3], dtype=float)
print('Float array:', float_arr)
print('Data type:', float_arr.dtype)

# Create boolean array
bool_arr = np.array([0, 1, 0, 1], dtype=bool)
print('Boolean array:', bool_arr)
print('Data type:', bool_arr.dtype)

# Create string array
str_arr = np.array(['cat', 'dog', 'bird'], dtype='U5')
print('String array:', str_arr)
print('Data type:', str_arr.dtype)
OutputSuccess
Important Notes

If you don't specify dtype, numpy guesses the type based on data.

Choosing the right dtype can save memory and speed up your program.

For strings, 'U' means Unicode and the number after it is max length.

Summary

Use dtype to control the type of data stored in numpy arrays.

Specifying dtype helps with memory and performance.

Common dtypes include int, float, bool, and string (Unicode).