Home > Enterprise >  Understanding np.ix_
Understanding np.ix_

Time:07-13

Code:

import numpy as np

ray = [1,22,33,42,51], [61,71,812,92,103], [113,121,132,143,151], [16,172,183,19,201]
ray = np.asarray(ray)
type(ray)

ray[np.ix_([-2:],[3:4])]

I'd like to use index slicing and get a subarray consisting of the last two rows and the 3rd/4th columns. My current code produces an error:

I'd also like to sum each column. What am I doing wrong? I cannot post a picture because I need at least 10 reputation points.

CodePudding user response:

So you want to make a slice of an array. The most straightforward way to do it is... slicing:

slice = ray[-2:,3:]

or if you want it explicitly

slice = ray[-2:,3:5]

See it explained in Understanding slicing

But if you do want to use np.ix_ for some reason, you need

slice = ray[np.ix_([-2,-1],[3,4])]

You can't use : here, because [] here don't make a slice, they construct lists and you should specify explicitly every row number and every column number you want in the result. If there are too many consecutive indices, you may use range:

slice = ray[np.ix_(range(-2, 0),range(3, 5))]

And to sum each column:

slice.sum(0)

0 means you want to reduce the 0th dimension (rows) by summation and keep other dimensions (columns in this case).

  • Related