配列の保存と読み込み

NumPy入門

Izzy Weber

Curriculum Manager, DataCamp

RGB 配列

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

上段が赤, 中段が緑, 下段が青の RGB データのプロット

NumPy入門

RGB 配列

ピンクや黄色などの混色が RGB データでどう表されるかを示す色分けコード断片 前画像のコードで作られた 3×3 の多色グリッド

NumPy入門

.npy ファイルの読み込み

 

配列は多様な形式で保存可能:

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

白背景に青い NumPy ロゴの画像

NumPy入門

RGB データの確認

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

3D の RGB 配列を赤・緑・青の 2D 配列に分割した図

NumPy入門

RGB データの確認

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]))
NumPy入門

RGB データの更新

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

先ほどの NumPy ロゴ。白背景が濃い灰色に置き換わっている

NumPy入門

.npy への保存

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

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...
NumPy入門

np.unique() の numpy.org ドキュメントのスクリーンショット

NumPy入門

メソッドでの help()

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- ...
NumPy入門

練習してみましょう!

NumPy入門

Preparing Video For Download...