Structured Arrays
Structured arrays are ndarrays with a composite datatype consisting of multiple named fields. They allow you to work with heterogeneous data (different data types) in a single array, similar to structs in C or database tables.Introduction
A structured array has a datatype composed of simpler datatypes organized as named fields.Accessing Fields
Creating Structured Datatypes
There are multiple ways to define structured dtypes.Method 1: List of Tuples
Method 2: Comma-Separated String
Method 3: Dictionary with Names and Formats
Method 4: Dictionary of Field Names
Field Titles
Fields can have both a name and a title (alternate name).Alignment and Padding
Structured dtypes can be aligned to match C struct layouts.Without Alignment
With Alignment
Nested Structures
Structured dtypes can be nested for hierarchical data.Indexing Structured Arrays
Single Field Access
Multiple Field Access
Boolean Indexing
Record Arrays
Record arrays (np.recarray) are structured arrays with field access via attributes.
Converting to Record Array
Record Arrays vs Structured Arrays
Record arrays allow field access via attributes (e.g.,
arr.field) but are slightly slower due to attribute lookup overhead.Structured arrays require indexing (e.g., arr['field']) but are faster.Use record arrays for convenience, structured arrays for performance.Practical Examples
Example 1: CSV-like Data
Example 2: Scientific Data
Example 3: C Struct Interfacing
Sorting Structured Arrays
Limitations and Considerations
Performance Trade-offs
Structured arrays can be slower than separate arrays for numerical operations due to memory layout. For intensive computations, consider using separate arrays and combining results.
Helper Functions
Summary
Heterogeneous Data
Store multiple data types in a single array with named fields
Field Access
Access data by field name, like database columns or struct members
C Interop
Match C struct layouts for binary data interfacing
Record Arrays
Convenient attribute access for structured arrays
See Also
- Data Types - Understanding NumPy dtypes
- Indexing - Advanced indexing techniques
- Array Creation - Creating arrays with various dtypes
