Creating Structured Array in Python NumPy

You can create a structured array in Python using the NumPy module. Follow the steps below to create a structured array:

Step 1: Import NumPy library

Step 2: Define the data type of structured array by creating a list of tuples, where each tuple contains the name of the field and its data type.

Step 3: You can now create the structured array using NumPy.array() method and set the dtype argument to the data type you defined in the previous step.

Example: Creating Structured Array in NumPy Python

Python3




import numpy as np
dt= np.dtype([('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], 
       dtype=dt)
  
print(a)


Output

[('Sana', 2, 21.0) ('Mansi', 7, 29.0)]



NumPy’s Structured Array | Create, Use and Manipulate Array

Numpy’s Structured Array is similar to the Struct in C. It is used for grouping data of different data types and sizes. 

Structured array uses data containers called fields. Each data field can contain data of any data type and size. 

Array elements can be accessed with the help of dot notation. For example, if you have a structured array “Student”, you can access the ‘class’ field by calling Student[‘class’].

Properties of Structured Array  

  • All structs in the array have the same number of fields.
  • All structs have the same field names.

For example, consider a structured array of students which has different fields like name, year, and marks. 

Each record in the array student has a structure of class Struct. The array of a structure is referred to as a struct as adding any new fields for a new struct in the array contains the empty array. 

Similar Reads

Creating Structured Array in Python NumPy

You can create a structured array in Python using the NumPy module. Follow the steps below to create a structured array:...

Structured Array Operations

...

Why use Structured Array?

Python offers many operations that you can perform on the structured array as a whole. These operations allow us to manipulate the entire structured array without worrying about individual fields....

Conclusion

...