
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Creating Structured Arrays
Introduction to Structured Arrays
Structured arrays in NumPy allow for the representation of data with different types and sizes in a single array. Each element in a structured array can be a record with multiple fields, each field having its own data type.
This is similar to having a table where each row represents a record with various attributes. The key points are as follows −
- Each element (record) in a structured array can have multiple fields.
- Fields can have different data types (e.g., integers, floats, strings).
- Structured arrays are useful for representing complex data structures.
Defining a Structured Array
The first step for creating a structured array is to define the data type for the structured array. This is done using a NumPy dtype object, which specifies the names and types of the fields in the array as shown in the following example −
import numpy as np # Define the data type for the structured array dtype = np.dtype([('name', 'U10'), ('age', 'i4'), ('height', 'f4')])
Here, dtype is a structured data type with three fields −
- name: A string of up to 10 characters ('U10')
- age: An integer ('i4')
- height: A floating-point number ('f4')
Creating the Structured Array
Once you have defined the "dtype", you can create the structured array by passing the dtype to the np.array() function. Following is the syntax −
numpy.array( object, dtype=None, copy=True, order='K', subok=False, ndmin=0 )
Where,
- object: This is the input data that you want to convert into a NumPy array. It can be a list, tuple, or any other sequence-like structure.
- dtype (Optional): This specifies the desired data type for the array. If not provided, NumPy will infer the data type from the input data. For example, you can use 'int32', 'float64', 'str', etc.
- copy (Optional): If True (default), a new array is created. If False, a new array is created only if necessary (i.e., if the input object is not already an array). If False, np.array may return a view of the original array if possible.
- order (Optional): This specifies the memory layout order. It can be 'C' for row-major (C-style) order, 'F' for column-major (Fortran-style) order, or 'K' for the order as found in the input. Default is 'K'.
- subok (Optional): If True, a subclass of ndarray will be used if the input is a subclass. Default is False, meaning the returned array will always be an instance of ndarray.
- ndmin (Optional): This specifies the minimum number of dimensions that the resulting array should have. For example, setting ndmin=2 ensures that the result is at least a 2-dimensional array.
Example
In the following example, we are defining a structured array with a specified dtype that includes fields for "name", "age", and "height". We then create the array with data matching this structure and print the resulting structured array −
import numpy as np # Define the dtype with field names and data types dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')] # Create data consistent with the dtype data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)] # Create the structured array structured_array = np.array(data, dtype=dtype) print("Structured Array:\n", structured_array)
Following is the output obtained −
Structured Array: [('Alice', 30, 5.6) ('Bob', 25, 5.8) ('Charlie', 35, 5.9)]
Create Structured Arrays with Different Data Types
You can create structured arrays with various data types, including strings, integers, and floats, depending on the needs of your application.
In the context of structured arrays −
- Strings: You can store text data in structured arrays. For example, a field for names might use a string data type.
- Integers: Numerical data, such as ages or counts, can be stored as integers. This might include data like age or quantity, which are whole numbers.
- Floats: For decimal numbers or real numbers, you can use float data types. This is useful for measurements or any value requiring precision, such as height or weight.
Example
In the following example, we are creating a structured array with a data type (dtype) that includes mixed data types: integers for IDs, strings for names, and floating-point numbers for scores −
import numpy as np # Define a dtype with mixed data types dtype = [('id', 'i4'), ('name', 'U15'), ('score', 'f8')] data = [(1, 'Alice', 88.5), (2, 'Bob', 91.2), (3, 'Charlie', 85.4)] # Create the structured array structured_array = np.array(data, dtype=dtype) print("Structured Array with Mixed Data Types:\n", structured_array)
This will produce the following result −
Structured Array with Mixed Data Types:[(1, 'Alice', 88.5) (2, 'Bob', 91.2) (3, 'Charlie', 85.4)]
Create Structured Arrays Using List of Tuples
You can define the dtype and create the structured array using a list of tuples, where each tuple represents a field. Each tuple contains two elements: the first element is the name of the field, and the second element is the data type of that field.
Example
In the following example, we are defining a structured array with fields for "name", "age", and "height" using a specified dtype. We then create this array with corresponding data −
import numpy as np # Define the dtype dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')] # Define the data data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)] # Create the structured array structured_array = np.array(data, dtype=dtype) print("Structured Array:\n", structured_array)
Following is the output obtained −
Structured Array: [('Alice', 30, 5.6) ('Bob', 25, 5.8) ('Charlie', 35, 5.9)]
Create Structured Arrays Using Dictionary
Alternatively, you can define the data and dtype using a dictionary to clearly specify the names and types of fields. Each key in the dictionary represents a field name, and the value associated with each key defines the data type of that field.
Example
In this example, we are defining the dtype for a structured array using a dictionary format to specify fields for "name", "age", and "height". We then create and display this structured array with the corresponding data, organizing it into a format that supports multiple data types within each record −
import numpy as np # Define the dtype using a dictionary dtype = np.dtype([('name', 'U10'), ('age', 'i4'), ('height', 'f4')]) # Define the data data = [('Alice', 30, 5.6), ('Bob', 25, 5.8), ('Charlie', 35, 5.9)] # Create the structured array structured_array = np.array(data, dtype=dtype) print("Structured Array from Dictionary:\n", structured_array)
This will produce the following result −
Structured Array from Dictionary: [('Alice', 30, 5.6) ('Bob', 25, 5.8) ('Charlie', 35, 5.9)]