w3resource

Save and load NumPy array to CSV with custom delimiter


20. Array Append to List Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a NumPy array to a list, append additional elements, and then convert the list back to an array verifying dimensions.
  • Write a Numpy program to append one NumPy array to another via a Python list intermediary and then perform a vectorized addition on the result.
  • Write a Numpy program to merge a Python list with a NumPy array by appending and then reshaping the combined structure into a matrix.
  • Write a Numpy program to append a multidimensional NumPy array to a list and then flatten the list into a single-dimensional array for further operations.

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.