How to save a NumPy array to a CSV File and verify contents?
NumPy: Interoperability Exercise-14 with Solution
Write a NumPy program to save a NumPy array to a CSV file and verify the contents by reading the file.
Sample Solution:
Python Code:
import numpy as np
import pandas as pd
# Create a NumPy array
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Save the NumPy array to a CSV file
np.savetxt('array.csv', array, delimiter=',')
# Read the CSV file to verify contents
verified_array = np.loadtxt('array.csv', delimiter=',')
# Print the original NumPy array
print("Original NumPy Array:")
print(array)
print(type(array))
# Print the verified NumPy array read from the CSV file
print("\nVerified NumPy Array from CSV File:")
print(verified_array)
print(type(verified_array))
Output:
Original NumPy Array: [[1 2 3] [4 5 6] [7 8 9]] <class 'numpy.ndarray'> Verified NumPy Array from CSV File: [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] <class 'numpy.ndarray'>
Explanation:
- Import NumPy and Pandas Libraries: Import the NumPy and Pandas libraries to work with arrays and data files.
- Create NumPy Array: Define a NumPy array with some example data.
- Save NumPy Array to CSV File: Use np.savetxt() to save the NumPy array to a CSV file named 'array.csv', specifying the delimiter as a comma.
- Read CSV File to Verify Contents: Use np.loadtxt() to read the contents of the CSV file back into a NumPy array, specifying the delimiter as a comma.
- Print Original NumPy Array: Output the original NumPy array to compare with the verified array.
- Print Verified NumPy Array: Output the NumPy array read from the CSV file to ensure the data was saved and retrieved accurately.
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