Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

example of structured array

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. 

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)]



Structured Array Operations

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.

Sorting Structured Array

The structure array can be sorted by using NumPy.sort() method and passing the order as the parameter. This parameter takes the value of the field according to which it is needed to be sorted.

Example: 

Python3




import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], 
       dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
               
# Sorting according to the name
b = np.sort(a, order='name')
print('Sorting according to the name', b)
  
# Sorting according to the age
b = np.sort(a, order='age')
print('\nSorting according to the age', b)


Output

Sorting according to the name [('Mansi', 7, 29.0) ('Sana', 2, 21.0)]

Sorting according to the age [('Sana', 2, 21.0) ('Mansi', 7, 29.0)]



Finding Min and Max in Structured Array

You can find the minimum and maximum of a structured array using the np.min() and np.max() functions and pass the fields in the function.

Example

Python3




import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], 
       dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])
               
max_age = np.max(a['age'])
min_age = np.min(a['age'])
  
print("Max age = ",max_age)
print("Min age = ", min_age)


Output

Max age =  7
Min age = 2

Concatenating Structured Array

You can use the np.concatenate() function to concatenate two structured arrays. Look at the example below showing the concatenation of two structured arrays.

Example

Python3




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


Output

[('Sana', 2, 21.) ('Mansi', 7, 29.) ('Ayushi', 5, 30.)]

Reshaping a Structured Array

You can reshape a structured array by using the NumPy.reshape() function.

Note: The total size of the structured array will remain the same.

Example

Python3




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


Output

[[('Sana', 2, 21.)]
[('Mansi', 7, 29.)]]

Why use Structured Array?

Structured arrays in NumPy allow us to work with arrays that contain elements of different data types. They are very useful in the case of tabular and structured data. Here are some uses of structured arrays:

Grouping Data

NumPy’s structured arrays allow us to group data of different data types and sizes. Each field in a structured array can contain data of any data type, making it a versatile tool for data grouping.

Tabular Data

Structured arrays can be a great tool when dealing with tabular data. They allow us to store and manipulate complex data structures with multiple fields, similar to a table or a spreadsheet.

Data Analysis

Structured arrays are very useful for data analysis. They provide efficient, flexible data containers that allow us to perform operations on entire datasets at once.

Memory efficiency

Structured arrays are memory-efficient. They allow us to store complex, heterogeneous data in a compact format, which can be important when working with large datasets.

Integrating with other libraries

Many Python libraries, such as Pandas and Scikit-learn, are built on top of NumPy and can work directly with structured arrays. This makes structured arrays a good choice when you need to integrate your code with other libraries.

Conclusion

Structured arrays are a very useful and convenient way of storing data. They allow us to store data with different data types, making them very useful for data science projects.

In this tutorial, we have explained NumPy’s structured array in simple words with examples. We have discussed the definition, operations, and benefits of using the structured array. This free guide will provide you with all the necessary information you need on structured arrays.



Last Updated : 02 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads