Numpy structured array is the same as the structure in C. It is a group of variables with different data types and sizes. In this entire tutorial, I will show you how to create a NumPy structured array and traversing it with step by step.
Step by Step to create a Numpy Structured Array
Step 1: The most basic step is to import NumPy library. It can be done using the import statement.
import numpy as np
Step 2: Define your datatype for the structured array.
In this step, you have to make a list of the set of the variable names and their type. The syntax for it is below.
It will be useful when you create an array and use it as dtype.
For Example, let’s create a structured array of students. It contains a name, rollno, and marks.
student_def = [("name","S10"),("roll","i8"),("marks","f8")]
Here S10, i8, f8 are data types for name, roll, and marks respectively. S10 represents a string with 10 characters. The i8, 8 digit integers, and f8, float of 8 digits.
Step 3: Create a zero array with the type defined in step 2.
Now let’s create a zero array of size 3 and define its type to students_def. You can create zero arrays by using the method zeros().
Execute the below code to create zero arrays of student_def type.
student_array = np.zeros((3),dtype=student_def)
You will get the following output.
This way you can create a NumPy structured array. In the next section, I will show you how to add or assign elements and traverse along with the array.
How to Assign and Traverse along with the Structured Array?
Now, let’s add some values inside the structured array created in the above steps. You can do so by selecting the index value. For example, I want to add values to 0 and 1 indexes. To do so I will use the python tuple.
student_array = ("Abhishek",1,95) student_array =("Sahil",10,90)
It will assign the values to the empty array. Now if you print the student_array then you will these values.
You can also look at the first value of student_array by using the index like below.
The other method to access the elements is the variable name. For example, I want to look at all the marks of the student. Then I will pass the marks inside the square bracket.
Execute the code below to get the output.
marks = student_array["marks"]
In the same way to extract the name of all the students.
name = student_array["name"]
That’s all for now.
These are steps to create and traverse inside the structured array. A structured Array is very useful if you want to group large data in one single array.
I hope this article has cleared your queries on the structured array. Even if you have any query then you can contact us for more information.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.