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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics