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

2 COMMENTS

Most Popular

Dominic
32713 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7088 POSTS0 COMMENTS
Nicole Veronica
12228 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12310 POSTS0 COMMENTS
Shaida Kate Naidoo
7203 POSTS0 COMMENTS
Ted Musemwa
7470 POSTS0 COMMENTS
Thapelo Manthata
7190 POSTS0 COMMENTS
Umr Jansen
7171 POSTS0 COMMENTS