w3resource

NumPy: Create a record array from a given regular array

NumPy: Array Object Exercise-190 with Solution

Write a NumPy program to create a record array from a given regular array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a NumPy array 'arra1' containing records with names and corresponding scores
arra1 = np.array([("Yasemin Rayner", 88.5, 90),
                 ("Ayaana Mcnamara", 87, 99),
                 ("Jody Preece", 85.5, 91)])

# Displaying the original array 'arra1'
print("Original arrays:")
print(arra1)

# Converting the array 'arra1' into a record array with named fields 'col1', 'col2', and 'col3'
result = np.core.records.fromarrays(arra1.T,
                                    names='col1, col2, col3',
                                    formats='S80, f8, i8')

# Displaying the record array 'result'
print("\nRecord array;")
print(result) 

Sample Output:

Original arrays:
[['Yasemin Rayner' '88.5' '90']
 ['Ayaana Mcnamara' '87' '99']
 ['Jody Preece' '85.5' '91']]

Record array;
[(b'Yasemin Rayner', 88.5, 90) (b'Ayaana Mcnamara', 87. , 99)
 (b'Jody Preece', 85.5, 91)]

Explanation:

In the above code –

arra1: A 2D NumPy array containing three rows, where each row represents a record with a name (string), and two numeric values.

arra1.T: Transposes arra1 to swap rows and columns so that each row now represents a column in the original arra1.

np.core.records.fromarrays: Creates a structured NumPy array (record array) from the given arrays. In this case, it takes the transposed arra1 as input.

names='col1, col2, col3': Sets the field names for the structured array.

formats='S80, f8, i8': Specifies the data types for each field in the structured array. 'S80' represents a string with a maximum length of 80 characters, 'f8' represents a 64-bit floating-point number, and 'i8' represents a 64-bit integer.

result: The resulting structured NumPy array stores in the variable "result".

print(result): Finally print() function prints the created structured NumPy array.

Python-Numpy Code Editor:

Previous:Write a NumPy program to find rows of a given array of shape (8,3) that contain elements of each row of another given array of shape (2,2).
Next: Write a NumPy program to get the block-sum (block size is 5x5) from a given array of shape 25x25.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.