w3resource

How to write a structured NumPy array to a CSV file with proper formatting?

NumPy: I/O Operations Exercise-4 with Solution

Write a structured NumPy array to a CSV file, ensuring proper formatting of different data types.

Sample Solution:

Python Code:

import numpy as np
import csv

# Create a structured NumPy array with different data types
data = np.array([
    (1, 'Zayden Jer', 86.5),
    (2, 'Luna Marci', 90.0),
    (3, 'Kord Shane', 88.0),
    (4, 'Coeus Zora', 91.5)
], dtype=[('ID', 'i4'), ('Name', 'U10'), ('Score', 'f4')])

# Define the path to the output CSV file
csv_file_path = 'structured_output.csv'

# Write the structured NumPy array to a CSV file
with open(csv_file_path, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    # Write the header
    writer.writerow(data.dtype.names)
    # Write the data rows
    for row in data:
        writer.writerow(row)

# Print a message indicating the CSV file has been written
print(f"Data has been written to {csv_file_path}")

Output:

Data has been written to structured_output.csv
Content of  structured_output.csv
ID,Name,Score
1,Zayden Jer,86.5
2,Luna Marci,90.0
3,Kord Shane,88.0
4,Coeus Zora,91.5

Explanation:

  • Import NumPy and CSV Libraries: Import the NumPy and CSV libraries to handle structured arrays and writing to CSV files.
  • Create a Structured NumPy Array: Define a structured NumPy array with different data types (integers, strings, and floats) for each column.
  • Define CSV File Path: Specify the path where the output CSV file will be saved.
  • Open CSV File for Writing: Open the CSV file in write mode using open(). Create a CSV writer object with the specified delimiter.
  • Write Header: Use writer.writerow() to write the column names (header) to the CSV file.
  • Write Data Rows: Iterate through each row of the structured NumPy array and write it to the CSV file using writer.writerow().
  • Finally output a message indicating that the data has been successfully written to the CSV file.

Python-Numpy Code Editor:

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

Previous: How to read data from a CSV file into a structured NumPy array?
Next: How to read a CSV file with missing values into a NumPy array?

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.