w3resource

How to write a NumPy array with Numeric and String data to a CSV file?

NumPy: I/O Operations Exercise-2 with Solution

Write a NumPy array with both numeric and string data to a CSV file.

Sample Solution:

Python Code:

import numpy as np
import csv

# Create a NumPy array with both numeric and string data
data_array = np.array([
    [1, 'Jorah Liina', 95.5],
    [2, 'Basil Aisha', 90.0],
    [3, 'Helga Myrthe', 80.0],
    [4, 'Lehi Piero', 91.5]
], dtype=object)

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

# Write the NumPy array to a CSV file
with open(csv_file_path, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for row in data_array:
        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 output.csv
Content of  output.csv
----------------------------
1,Jorah Liina,95.5
2,Basil Aisha,90.0
3,Helga Myrthe,80.0
4,Lehi Piero,91.5

Explanation:

  • Import NumPy and CSV Libraries: Import the NumPy and CSV libraries to handle arrays and writing to CSV files.
  • Create a NumPy Array: Define a NumPy array with mixed data types (both numeric and string data), specifying dtype=object to handle different types within the array.
  • Define CSV File Path: Specify the path where the output CSV file will be saved.
  • Write Array to CSV File: Open the CSV file in write mode using open() and csv.writer(). Iterate through each row of the NumPy array and write it to the CSV file using writer.writerow().
  • Finally 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 numeric data from a CSV file into a NumPy array?
Next: Convert Pandas DataFrame to NumPy array and print.

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://198.211.115.131/python-exercises/numpy/write-a-numpy-array-with-numeric-and-string-data-to-a-csv-file.php