w3resource

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.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to convert a 2D array into a record array with named fields using np.core.records.fromarrays.
  • Create a function that assigns custom field names to columns of a given array and returns a structured record array.
  • Implement a solution that converts a regular array into a recarray and accesses fields by attribute.
  • Test the conversion on arrays with mixed data types and verify the resulting record array’s structure.

Go to:


PREV : Find rows containing elements of another array.
NEXT : Compute block-sum of a 25x25 matrix (e.g., sum of each 5x5 block).


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.