保存与加载数组

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 数据中的表示 由上一图代码生成的三乘三多色网格

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 入门

Passons à la pratique !

NumPy 入门

Preparing Video For Download...