w3resource

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


4. Structured Array CSV Write

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to export a structured array with various data types to a CSV file while ensuring correct formatting for each type.
  • Write a Numpy program to write a structured array to CSV and then re-import it, validating that the data types remain consistent.
  • Write a Numpy program to format a structured array into CSV with headers and footers, then compare the output with a manual format.
  • Write a Numpy program to write a structured array to a CSV file and then modify the CSV by adding a new column via external processing.

Go to:


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?

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.