Spara och läsa in arrayer

Introduktion till NumPy

Izzy Weber

Curriculum Manager, DataCamp

RGB-arrayer

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()

Plottad RGB-data med röd överst, grön i mitten och blå längst ner

Introduktion till NumPy

RGB-arrayer

Ett färgkodat kodexempel som visar hur blandade färger som rosa och gul representeras i RGB-data Flerfärgat tre-gånger-tre-rutnät skapat av koden i föregående bild

Introduktion till NumPy

Läsa in .npy-filer

 

Spara arrayer i många format:

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

Bild av den blå NumPy-logotypen mot vit bakgrund

Introduktion till NumPy

Utforska RGB-data

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

En 3D RGB-array uppdelad i tre 2D-arrayer: en röd, en grön och en blå

Introduktion till NumPy

Utforska 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]))
Introduktion till NumPy

Uppdatera RGB-data

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

Samma NumPy-logotyp som tidigare men med mörkgrå bakgrund istället för vit

Introduktion till NumPy

Spara arrayer som .npy-filer

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

Om du behöver 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...
Introduktion till NumPy

En skärmbild av numpy.org-dokumentationen för np.unique()

Introduktion till NumPy

help() med metoder

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- ...
Introduktion till NumPy

Nu kör vi en övning!

Introduktion till NumPy

Preparing Video For Download...