2

...couldn't find an answer so hope its not a duplicate...

I have an array arr and want to select a sub-array sub_arr using specified indices (e.g. idxs = [1,3,4,6]). My inuition was to set sub_arr = arr[idxs,idxs], however this returns a 1-D array with of diagonals (e.g. entries at (1,1), (3,3), ...). I can get what I'm after by first setting sub_arr = arr[:,idxs] and then sub_arr = sub_arr[idxs,:].

My questions are:

(1) Why does the first method do not do what the second does?

(2) Is there a neat way, i.e. all in one line like the first method, to get the result of the second method?

Many thanks in advance

Input

arr = np.random.rand(8,8)

# Indexes for sub-array
idxs = [1,3,4,6]

# What ought to work but doesn't
sub_arr1 = arr[idxs,idxs]

# What works
sub_arr2 = arr[:,idxs]
sub_arr2 = sub_arr2[idxs,:]

print('The array is ')
print(arr)
print('\n')
print('Sub-array 2 shape is ', sub_arr2.shape)
print('Sub_array 2 is ')
print(sub_arr2)
print('\n')
print('Sub-array 1 shape is ', sub_arr1.shape)
print('Sub_array 1 is ')
print(sub_arr1)

Output

The array is 
[[9.66147446e-01 7.91879570e-01 6.75689148e-01 2.44889479e-01
  2.16457261e-01 1.66047825e-01 9.22756610e-01 2.94076662e-01]
 [4.53094245e-01 4.93957834e-01 7.78171595e-01 8.44234962e-01
  1.39072701e-01 4.26904360e-01 8.42854888e-01 8.18033306e-01]
 [1.02413758e-01 1.56383349e-01 3.04198692e-01 7.53590691e-02
  4.24663003e-01 1.07617705e-01 5.68217594e-01 2.46556940e-01]
 [5.96433065e-01 1.17525643e-01 9.75883868e-01 9.32561204e-01
  3.91796939e-01 2.42178594e-01 2.50398213e-01 4.83393535e-01]
 [3.99928019e-02 6.39705106e-01 4.08302908e-01 3.77406573e-01
  8.09364971e-01 7.09035460e-01 9.54333815e-01 3.51936240e-01]
 [8.97542765e-01 7.69967186e-01 3.57424652e-01 6.21665436e-01
  2.88569958e-01 8.74399917e-01 1.12427317e-01 2.12434361e-01]
 [1.83033292e-01 4.03026002e-01 7.45232960e-01 5.26907449e-01
  4.87676324e-01 5.45964897e-04 4.25401725e-01 6.35537748e-02]
 [2.08253252e-01 9.32393939e-01 2.15398204e-01 8.58337639e-01
  8.02893372e-01 1.59146237e-01 6.05711957e-01 1.15661872e-01]]


Sub-array 2 shape is  (4, 4)
Sub_array 2 is 
[[0.49395783 0.84423496 0.1390727  0.84285489]
 [0.11752564 0.9325612  0.39179694 0.25039821]
 [0.63970511 0.37740657 0.80936497 0.95433382]
 [0.403026   0.52690745 0.48767632 0.42540173]]


Sub-array 1 shape is  (4,)
Sub_array 1 is 
[0.49395783 0.9325612  0.80936497 0.42540173]

0 Answers0