Skip to content
Related Articles

Related Articles

Python: Numpy’s Structured Array
  • Last Updated : 14 Jan, 2020

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 fileds 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to dmeonstrate
# 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)

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :