[Python's numpy library] 13. Retain the dimension when taking a part of the array

If it solves your problem, please give a like and go ٩(๑❛ᴗ❛๑)۶

When we operate on a two-dimensional array, we want to take a row or a column, but it will automatically become one-dimensional after taking it out . What if you want to preserve the 2D dimension ?

The method is to add None , see the code for details

import numpy as np

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9],
              [1, 2, 3]])

print('a=\n', a)

print('\na[:, 2]=\n', a[:, 2])
print('\na[:, 2, None]=\n', a[:, 2, None])

print('\na[2, :]=\n', a[2, :])
print('\na[2, None, :]=\n', a[2, None, :])

result:

a=
 [[1 2 3]
 [4 5 6]
 [7 8 9]
 [1 2 3]]

a[:, 2]=
 [3 6 9 3]

a[:, 2, None]=
 [[3]
 [6]
 [9]
 [3]]

a[2, :]=
 [7 8 9]

a[2, None, :]=
 [[7 8 9]]

Guess you like

Origin blog.csdn.net/m0_53392188/article/details/119742864