Menu
×
×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS NUMPY FOR ML Roadmap
     ❯   

ADVANCED NUMPY OPERATIONS

File I/O Operations with NumPy

×

Share this Topic

Share Via:

Thank you for sharing!


Saving and Loading Arrays

NumPy allows us to save and retrieve arrays efficiently in binary or text format.

a) Saving and Loading a NumPy Array (Binary Format)

# Create an array
a = np.array([1, 2, 3, 4, 5])
# Save array to a binary file
np.save('data.npy', a)
# Load the array from the file
b = np.load('data.npy')
print("Loaded Array:", b)

Why Use .npy Format?

  • Stores data in a compact binary format.
  • Faster loading and saving compared to CSV or text files.
  • Retains data type and structure of arrays.

b) Saving and Loading Multiple Arrays

We can save multiple arrays in a single file using np.savez().

# Create multiple arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([10, 20, 30])
# Save both arrays in a single file
np.savez('multi_data.npz', array1=arr1, array2=arr2)
# Load the arrays from file
loaded_data = np.load('multi_data.npz')
print("Array 1:", loaded_data['array1'])
print("Array 2:", loaded_data['array2'])

When to Use .npz Format?

  • When working with large datasets where multiple arrays need to be stored efficiently.
  • Reduces disk space usage while maintaining fast I/O speeds.

c) Saving and Loading CSV Files

Many real-world datasets are stored in CSV format. NumPy makes it easy to save and load CSV files.

Saving a NumPy Array as a CSV File

# Create a sample array
data = np.array([[1, 2, 3], [4, 5, 6]])
# Save to CSV
np.savetxt('data.csv', data, delimiter=',')

Loading Data from a CSV File

# Load CSV file
loaded_data = np.loadtxt('data.csv', delimiter=',')
print("Loaded CSV Data:\n", loaded_data)

Use Case:

  • CSV files are widely used in data science, machine learning, and finance.

Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2025 Django-tutorial.dev .All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.