简体   繁体   中英

How to mask a “crop” a multi dimensional numpy array by N dimensions?

say I have an array a, that can be N dimensional, but for simplicities sake let's say its:

a = np.array([[0,1,2],
             [3,4,5]])

I also have a mask or crop(I dont know the proper term) that is has the length of N, so in this case something like:

b = [1,2]

How can I "crop" the array so its:

a = a[:b]

which would slice a the same as:

a = a[:1,:2]

but would work no matter the value of N.

Use slice notation -

a[tuple([slice(None,bi) for bi in b])]

Or with its shorthand np.s_ -

a[tuple([np.s_[:bi] for bi in b])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM