np.newaxis role

The role of np.newaxis: insert a new dimension

First look at the following examples:

example 1:

# In:
arr = np.array([1,2,3,4,5])
print(arr.shape)
print(arr)

# Out:
(5,)
[1,2,3,4,5]

example 2:

# In:
arr = np.array([1,2,3,4,5])
arr1 = arr[:, np.newaxis]
print(arr1.shape)
print(arr1)

# Out:
(5,1)
[[1],
 [2],
 [3],
 [4],
 [5]]

example 3:

# In:
arr = np.array([1,2,3,4,5])
arr2 = arr[np.newaxis, :]
print(arr2.shape)
print(arr2)

#Out:
(1,5)
[[1,2,3,4,5]]

As shown in the above example, the role of np.newaxis is to add a dimension

Corresponding to [: ,np.newaxis] and [np.newaxis, :]:

It is to add 1 dimension to the position of np.newaxis.

If you still feel unclear, please see the following example:

example 4:

# In:
arr = np.array([1,2,3,4,5])
print(arr.shape)
print(arr)

# Out:
(5,)
[1,2,3,4,5]

# In:
arr1 = arr[np.newaxis, :]
print(arr1.shape)
print(arr1)

#Out:
(1,5)
[[1,2,3,4,5]]

# In:
arr2 = arr1[np.newaxis, :]
print(arr2.shape)
print(arr2)

#Out:
(1,5)
[[[1,2,3,4,5]]]

# In:
arr3 = arr2[:, :, :, np.newaxis]
print(arr3.shape)
print(arr3)

#Out:
(1,5)
[[[[1],
   [2],
   [3],
   [4],
   [5]]]]

Guess you like

Origin blog.csdn.net/qq_42546127/article/details/112885874