w3resource

Load data from CSV file into NumPy Structured array

NumPy: Structured Arrays Exercise-14 with Solution

Loading Data from a CSV File:

Write a NumPy program that loads data from a CSV file into a structured array. Assume the CSV file has columns corresponding to 'name', 'age', and 'height'.

Sample Solution:

Python Code:

import numpy as np

# Define the data type for the structured array
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]

# Load data from the CSV file into a structured array
# Assume the CSV file is named 'data.csv' and is in the same directory
structured_array = np.genfromtxt('data.csv', delimiter=',', dtype=dtype, names=True)

# Print the structured array loaded from the CSV file
print("Structured Array loaded from 'data.csv':")
print(structured_array)

Output:

Structured Array loaded from 'data.csv':
[('Albin Acha', 30, 5.8) ('Zerach Hav', 35, 6.1) ('Edmund Ter', 40, 5.9)
 ('Laura Feli', 28, 5.7)]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Define Data Type:
    • Define the data type for the structured array using a list of tuples. Each tuple specifies a field name and its corresponding data type. The data types are:
      • 'U10' for a string of up to 10 characters.
      • 'i4' for a 4-byte integer.
      • 'f4' for a 4-byte float.
  • Load Data from CSV File:
    • Used "np.genfromtxt()" to load data from the CSV file named 'data.csv' into a structured array. The parameters used are:
      • 'data.csv': Name of the CSV file.
      • delimiter=',': Specifies that the file is comma-separated.
      • dtype=dtype: Specifies the data type for the structured array.
      • names=True: Indicates that the first row of the CSV file contains the column names.
  • Finally print the structured array loaded from the CSV file to verify the operation.

Python-Numpy Code Editor:

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

Previous: Rename fields in NumPy Structured array.
Next: Save NumPy Structured array to a file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/load-data-from-csv-file-into-numpy-structured-array.php