Saving and loading arrays

Introduction to NumPy

Izzy Weber

Curriculum Manager, DataCamp

RGB arrays

rgb = np.array([[[255, 0, 0], [255, 0, 0], [255, 0, 0]],
                [[0, 255, 0], [0, 255, 0], [0, 255, 0]],
                [[0, 0, 255], [0, 0, 255], [0, 0, 255]]])
plt.imshow(rgb)
plt.show()

Plotted RGB data with red on the top row, green in the middle, and blue at the bottom

Introduction to NumPy

RGB arrays

A color-coded code snippet showing how mixed colors such as pink and yellow are represented in RGB data Multicolored three by three grid of colors created by code in the previous image

Introduction to NumPy

Loading .npy files

 

Save arrays in many formats:

  • .csv
  • .txt
  • .pkl
  • .npy
with open("logo.npy", "rb") as f:
    logo_rgb_array = np.load(f)
plt.imshow(logo_rgb_array)
plt.show()

Image of blue NumPy logo on white background

Introduction to NumPy

Examining RGB data

red_array = logo_rgb_array[:, :, 0]
blue_array = logo_rgb_array[:, :, 1]
green_array = logo_rgb_array[:, :, 2]

A 3D RGB array sliced into three 2D arrays: one red, one green, and one blue

Introduction to NumPy

Examining RGB data

red_array[1], green_array[1], blue_array[1]
(array([255, 255, 255, ..., 255, 255, 255]),
 array([255, 255, 255, ..., 255, 255, 255]),
 array([255, 255, 255, ..., 255, 255, 255]))
Introduction to NumPy

Updating RGB data

dark_logo_array = np.where(logo_rgb_array == 255, 50, logo_rgb_array)
plt.imshow(dark_logo_array)
plt.show()

The same NumPy logo we saw earlier but with a dark gray background instead of a white one

Introduction to NumPy

Saving arrays as .npy files

with open("dark_logo.npy", "wb") as f:
    np.save(f, dark_logo_array)
Introduction to NumPy

If we need help()...

help(np.unique)
Help on function unique in module numpy:
unique(ar, return_index=False, return_inverse=False, return_counts=False,
        axis=None)

Find the unique elements of an array.

Returns the sorted unique elements of an array. There are three optional
outputs in addition to the unique elements:

* the indices of the input array that give the unique values...
Introduction to NumPy

A screen shot of the numpy.org documentation for np.unique()

Introduction to NumPy

help() with methods

help(np.ndarray.flatten)
Help on method_descriptor: flatten(...)
a.flatten(order='C')

Return a copy of the array collapsed into one dimension.

Parameters
<hr />-------
order : {'C', 'F', 'A', 'K'}, optional
    'C' means to flatten in row-major (C-style) order.
    'F' means to flatten in column-major (Fortran- ...
Introduction to NumPy

Let's practice!

Introduction to NumPy

Preparing Video For Download...