Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
NumPy Copy and View of Array
Next article icon

numpy.fromrecords()method is a powerful tool in the NumPy library that allows you to create structured arrays from a sequence of tuples or other array-like objects.

Let's understand the help of an example:

Python
importnumpyasnp# Define a list of recordsrecords=[(1,'Alice',25.5),(2,'Bob',30.0),(3,'Charlie',28.0)]# Define the data typedtype=[('id','i4'),('name','U10'),('age','f4')]# Create the structured arraystructured_array=np.fromrecords(records,dtype=dtype)print(structured_array)

Output:

[(1, 'Alice', 25.5) (2, 'Bob', 30. ) (3, 'Charlie', 28. )]

Syntax of Numpy fromrecords():

numpy.fromrecords(recList, dtype=None, shape=None, aligned=False, byteorder=None)

Parameters:

  • recList: A list oftuples or structured data to be converted into a structuredNumPy array.
  • dtype(optional): The data type of the resulting structured array. If not provided, NumPy will infer the type from the input data.
  • shape(optional): Shape of the output array. Defaults to one-dimensional.
  • aligned(optional):IfTrue, aligns fields to their natural alignment.
  • byteorder(optional): Specifies the byte order of the output array.

Accessing Structured Array Fields

We can access specific fields (columns) in the structured array by their names.

Python
importnumpyasnp# Define a list of recordsrecords=[(1,'Alice',25.5),(2,'Bob',30.0),(3,'Charlie',28.0)]# Define the data typedtype=[('id','i4'),('name','U10'),('age','f4')]# Create the structured arraystructured_array=np.fromrecords(records,dtype=dtype)# Access the 'name' fieldprint(structured_array['name'])# Access the 'age' fieldprint(structured_array['age'])

Output:

[(1, 'Alice', 25.5) (2, 'Bob', 30. ) (3, 'Charlie', 28. )]

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp