numpy advance index

# https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing
# tips: torch.tensor has the same indexing rules as numpy.ndarray

import numpy as np

a = np.array([
[11,12,13,14,15,16,17],
[21,22,23,24,25,26,27],
[31,32,33,34,35,36,37],
[41,42,43,44,45,46,47],
[51,52,53,54,55,56,57],
])
a[np.array([0,2,4])]
a[np.array([0,2,4])].shape
# 2D index will change data shape
a[np.array([0,2,4]).reshape(-1,1)]
a[np.array([0,2,4]).reshape(-1,1)].shape
# 2D index as first index, can work with second array as index
a[np.array([0,2,4]).reshape(-1,1), np.array([1,3,5])]
a[np.array([0,2,4]).reshape(-1,1), np.array([1,3,5])].shape
# np.where result as index
idx = np.where(a[:,2]>30)[0]
a[idx.reshape(-1,1),2:6].shape != a[idx.reshape(-1,1),range(2,6)].shape == a[idx,2:6].shape == a[idx][:,2:6].shape
# boolean result as index
idx = a[:,2]>30
idx.shape # idx == array([False, False, True, True, True])
a[idx,2:6] # shape==(3,4)
a[idx.reshape(1,-1)] # this is Not work for boolean index!
# assign value bug!
idx = np.where(a[:,2]>30)[0]
a[idx.reshape(-1,1),range(2,6)] = 9 # work
a[idx.reshape(-1,1),range(2,6)]
a[idx][:,2:6] = 9 # not work!!!
a[idx][:,2:6]

Add a Comment

Your email address will not be published. Required fields are marked *

1 × one =