w3resource

Save and load NumPy array to CSV with custom delimiter

NumPy: I/O Operations Exercise-20 with Solution

Write a NumPy array to a CSV file with a custom delimiter and then read it back into a NumPy array using the same delimiter.

Sample Solution:

Python Code:

import numpy as np

# Create a NumPy array
array_to_save = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Define the file name to save the CSV file
csv_file_name = 'array_data.csv'

# Save the NumPy array to a CSV file with a custom delimiter
np.savetxt(csv_file_name, array_to_save, delimiter=';', fmt='%d')

# Load the data back from the CSV file using the same delimiter
loaded_array = np.loadtxt(csv_file_name, delimiter=';')

# Print the loaded array to verify it matches the original array
print('Loaded array:\n', loaded_array)

Output:

Loaded array:
 [[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]]

Explanation:

  • Import Libraries:
    • Imported numpy as np for handling arrays and file operations.
  • Create NumPy Array:
    • Created a 3x3 NumPy array named array_to_save.
  • Define File Name:
    • Set the CSV file name to array_data.csv.
  • Save Array to CSV with Custom Delimiter:
    • Used np.savetxt to save array_to_save to the CSV file, specifying ; as the custom delimiter and formatting the numbers as integers ('%d').
  • Load Data from CSV with Same Delimiter:
    • Used np.loadtxt to read the data from the CSV file into loaded_array, using ; as the delimiter.
  • Print Loaded Array:
    • Printed the loaded array to verify it matches the original array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Save a NumPy array as an image file using Python.

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.