NumPy Input / Output (I/O)

In real-world data analysis, data rarely comes directly as NumPy arrays.

Most of the time, data is stored in files, such as text files, CSV files, or binary formats.

NumPy provides efficient input and output (I/O) functions to :

Understanding NumPy I/O is essential for building real data pipelines.



Why NumPy I/O Is Important

NumPy I/O helps you :

Without I/O, analysis cannot move beyond small examples.



Saving NumPy Arrays to Files

Saving a Single Array Using save( )

import numpy as np
arr = np.array([10, 20, 30, 40])
np.save("data.npy", arr)

This saves the array in a binary format, which is :



Loading NumPy Arrays Using load( )

loaded_arr = np.load("data.npy")
print(loaded_arr)

The array is restored exactly as it was saved.


Saving Multiple Arrays Using savez()

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.savez("multiple_arrays.npz", arr1=a, arr2=b)

This is useful when working with :


Loading Multiple Arrays

data = np.load("multiple_arrays.npz")
print(data["arr1"])
print(data["arr2"])


Working with Text Files

Saving Data to a Text File

arr = np.array([100, 200, 300])
np.savetxt("values.txt", arr)

Text files are human-readable but :


Loading Data from a Text File

arr = np.loadtxt("values.txt")
print(arr)


Working with CSV Files

CSV files are very common in analytics.

Loading a CSV File

data = np.loadtxt("sales.csv", delimiter=",")
print(data)

Useful when :


Handling Missing Values in Files

data = np.loadtxt("data.csv", delimiter=",", skiprows=1)

This skips header rows when loading data.


Real-Life Example: Loading Sales Data

sales = np.loadtxt("monthly_sales.csv", delimiter=",")
total_sales = np.sum(sales)
print("Total Sales:", total_sales)

This is a common analytics workflow :

  1. Load data
  2. Analyze
  3. Save results


Binary vs Text File Formats

Binary Files (.npy, .npz)


Text Files (.txt, .csv)

Choosing the right format improves performance.



Common Beginner Mistakes

Understanding I/O prevents data loss and errors.



Why NumPy I/O Matters in Data Analytics

NumPy I/O is used in :

Efficient data loading and saving saves time and resources.



Key Takeaways



Conclusion

NumPy Input and Output functions make it easy to work with real-world data stored in files. They allow you to efficiently load data, save processed results, and reuse arrays without losing structure or performance. By choosing the right file format and using NumPy’s I/O tools correctly