NumPy: Create a record array from a given regular array
Create a record array from a regular array.
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics