Saturday, September 21, 2024
Google search engine
HomeLanguagesPython: Numpy’s Structured Array

Python: Numpy’s Structured Array

Numpy’s Structured Array is similar to Struct in C. It is used for grouping data of different types and sizes. Structure array uses data containers called fields. Each data field can contain data of any type and size. Array elements can be accessed with the help of dot notation.
Note: Arrays with named fields that can contain data of various types and sizes.
Properties of Structured array 
 

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

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

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

Python3




# Python program to demonstrate
# Structured array
 
 
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)])
 
print(a)


Output: 

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

 

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

Python3




# Python program to demonstrate
# Structured array
 
 
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)]

 

RELATED ARTICLES

Most Popular

Recent Comments