Stacking and splitting

Introduzione a NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

Slicing dimensions

rgb = np.array([[[255, 0, 0], [255, 255, 0], [255, 255, 255]],
                [[255, 0, 255], [0, 255, 0], [0, 255, 255]],
                [[0, 0, 0], [0, 255, 255], [0, 0, 255]]])
red_array = rgb[:, :, 0]
green_array = rgb[:, :, 1]
blue_array = rgb[:, :, 2]
red_array
array([[255, 255, 255],
       [255,   0,   0],
       [0,   0,   0]])
Introduzione a NumPy

Splitting arrays

red_array, green_array, blue_array = np.split(rgb, 3, axis=2)
red_array
array([[[255], [255], [255]],
       [[255], [  0], [  0]],
       [[  0], [  0], [  0]]])
red_array.shape
(3, 3, 1)
Introduzione a NumPy

Trailing dimensions

red_array_2D = red_array.reshape((3, 3))
red_array_2D
array([[255, 255, 255],
       [255,   0,   0],
       [  0,   0,   0]])
red_array_2D.shape
(3, 3)
Introduzione a NumPy

Array division rules

red_array, green_array, blue_array = np.split(rgb, 5, axis=2)
ValueError: array split does not result in an equal division
Introduzione a NumPy

Stacking arrays

  Stacking two 2D arrays on top of each other creates a 3D array

Introduzione a NumPy

Plotting 2D image data

red_array, green_array, blue_array = np.split(logo_rgb_array, 3, axis=2)
plt.imshow(red_array)
plt.show()

A plot of the red values from NumPy's logo

Introduzione a NumPy

Stacking 2D arrays

red_array = np.zeros((1001, 1001)).astype(np.int32)
green_array = green_array.reshape((1001, 1001))
blue_array = blue_array.reshape((1001, 1001)) 
Introduzione a NumPy

Stacking 2D arrays

stacked_rgb = np.stack([red_array, green_array, blue_array], axis=2)
plt.imshow(stacked_rgb)
plt.show()

A picture of the NumPy logo with all red RGB values replaced with zeros

Introduzione a NumPy

Let's practice!

Introduzione a NumPy

Preparing Video For Download...