In this article we will discuss what is a structured numpy array and how to create it and sort it using different functions.

What is a Structured Numpy Array ?

A Structured Numpy Array is an array of structures (Similar to C struct). As numpy arrays are homogeneous i.e. they can contain data of same type only. So, instead of creating a numpy array of int or float, we can create numpy array of homogeneous structures too.

Let’s understand by an example,
Suppose we want to create a numpy array with elements of following structure

It means each element in numpy array should be a structure of above type. This kind of numpy arrays are called structured numpy arrays.
Let’s see how to create that,

Creating a Structured Numpy Array

First of all import numpy module i.e.

Now to create a structure numpy array we can pass a list of tuples containing the structure elements i.e.

But as elements of a numpy array are homogeneous, so how will be the size and type of structure will be decided ?
For that we need to pass the type of above structure type i.e. schema in dtype parameter. Let’s create a dtype for above structure i.e.

Let’s create a numpy array based on this dtype i.e.

It will create a structured numpy array and its contents will be,

Let’s check the data type of the above created numpy array is,

Output:

It is basically the structure type specifying a structure of String of size 10, float and int.

How to Sort a Structured Numpy Array ?

Suppose we have a very big structured numpy array and we want to sort that numpy array based on specific fields of the structure. For this,
both numpy.sort() and numpy.ndarray.sort() provides a parameter ‘order‘ , in which it can accept a single argument or list of arguments. Then it will sort the structured numpy array by this given order parameter as field of structure.

Let’s see how to do that,

Sort the Structured Numpy array by field ‘Name‘ of the structure

Output:

It sorted all the elements in this structured numpy array based on first field of the structure i.e. ‘Name’.

Sort the Structured Numpy array by field ‘Marks‘ of the structure

Output:

It sorted all the elements in this structured numpy array based on second field of the structure i.e. ‘Marks’.

Sort the Structured Numpy array by ‘Name’ & ‘GradeLevel’ fields of the structure

Output:

It sorted all the elements in this structured numpy array based on multiple fields of the structure i.e. ‘Name’ and ‘GradeLevel’.

Structured numpy arrays are useful when you want to load a big csv file in a single numpy array and perform operations on it.

Complete example is as follows,

Output:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,