0
0
NumPydata~5 mins

Defining structured dtypes in NumPy

Choose your learning style9 modes available
Introduction

Structured dtypes let you store different types of data together in one array, like a table with columns.

You want to store a list of people with their name, age, and height in one array.
You need to keep track of different measurements with labels and values in a single array.
You want to read or write data that has multiple fields, like a CSV with mixed data types.
You want to perform fast operations on columns of mixed data types without using a full database.
Syntax
NumPy
dtype = np.dtype([('field1', type1), ('field2', type2), ...])
Each field has a name and a data type.
Data types can be standard numpy types like 'int32', 'float64', or fixed-length strings like 'S10'.
Examples
This defines a structured dtype with three fields: name (string), age (integer), and height (float).
NumPy
dtype = np.dtype([('name', 'S10'), ('age', 'int32'), ('height', 'float64')])
Another way to define a structured dtype using a dictionary with field names and formats.
NumPy
dtype = np.dtype({'names': ['x', 'y'], 'formats': ['int32', 'int32']})
A simple structured dtype with two fields: id and score.
NumPy
dtype = np.dtype([('id', 'int32'), ('score', 'float64')])
Sample Program

This code creates a structured array with fields for name, age, and height. It then prints the whole array, the ages of all people, and the first person's name decoded from bytes to string.

NumPy
import numpy as np

# Define structured dtype for a person
person_dtype = np.dtype([('name', 'S10'), ('age', 'int32'), ('height', 'float64')])

# Create an array of 3 people
people = np.array([(b'Alice', 25, 5.5), (b'Bob', 30, 6.0), (b'Carol', 22, 5.7)], dtype=person_dtype)

# Print the whole array
print(people)

# Access the 'age' field for all people
print(people['age'])

# Access the first person's name
print(people[0]['name'].decode('utf-8'))
OutputSuccess
Important Notes

Strings in structured dtypes are stored as bytes, so you may need to decode them to get normal text.

You can access each field like a column in a table using the field name.

Structured arrays are useful for small to medium datasets with mixed data types.

Summary

Structured dtypes let you combine different data types in one array.

Define them by listing field names and their types.

You can access each field separately like columns in a table.