w3resource

How to save a NumPy array to a CSV File and verify contents?


14. Array to CSV Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to save a multidimensional NumPy array to a CSV file with a custom delimiter and then verify the shape upon reloading.
  • Write a Numpy program to export a structured NumPy array to CSV and then read it back while preserving column data types.
  • Write a Numpy program to write a NumPy array to a CSV file with headers and footers, then validate the written content by parsing the file.
  • Write a Numpy program to save a large NumPy array to CSV in chunks and then combine the chunks back into a single array for verification.

Go to:


Previous: How to convert a Pandas DataFrame to a NumPy array and back?
Next: How to read a CSV file into a NumPy array and print it?

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.