结合切片和广播的索引多维numpy的阵列 [英] Combining slicing and broadcasted indexing for multi-dimensional numpy arrays
问题描述
我有一个ND numpy的阵列(让说,例如3x3x3的)从至极,我想提取子阵列,结合片和数组索引。例如:
导入numpy的是NP
A = np.arange(3 * 3 * 3).reshape((3,3,3))
I0,I1,I2 =([0,1],[0,1,2],[0,2])
IND1 = J0,J1,J2 = np.ix_(I0,I1,I2)
IND2 =(J0,切片(无),J2)
B1 = A [IND1]
B2 = A [IND2]
我预计B1 B2 ==,但实际上,形状不同
>>> B1.shape
(2,3,2)
>>> B2.shape
(2,1,2,3)
>>> B1
阵列([[[0,2],
[3,5]
[6,8], [9,11],
[12,14],
[15,17]]])
>>> B2
阵列([[[[0,3,6]
[2,5,8]]], [[[9,12,15],
[11,14,17]]]])
有人明白为什么呢?任何想法我怎么可能通过操纵只'A'和'IND2对象得到'B1'?我们的目标是,这将适用于任何次阵列,而且我也不会找我的尺寸要完全保持的形状(希望我不够清楚:))。谢谢!结果
---编辑---结果
为了更清楚,我想有一个函数'有趣',使得
A [乐趣(IND2)] == B1
在受限制的索引情况下,像这样使用九_
,这是可以做到的索引在连续的步骤。
A [IND1]
是相同的
A [I1] [:, 12] [:,:,I3]
和自 I2
是品种齐全,
A [I1] [...,I3]
如果你只有 IND2
可用
A [IND2 [0] .flatten()] [IND2 [2] .flatten()]
在更广泛的背景下,你必须知道如何 J0,J1,J2
与对方,但播出时,它们是由生成IX _
,关系很简单。
我可以想象它会是方便的分配情况 A1 = A [I1]
,其次是各种涉及行动 A1
,包括但不限于 A1 [...,I3]
。你要知道,当 A1
是一个观点,当它是一个副本。
另一个索引工具是取
:
A.take(I0,轴= 0)。取(I2,轴= 2)
I have a ND numpy array (let say for instance 3x3x3) from wich I'd like to extract a sub-array, combining slices and index arrays. For instance:
import numpy as np
A = np.arange(3*3*3).reshape((3,3,3))
i0, i1, i2 = ([0,1], [0,1,2], [0,2])
ind1 = j0, j1, j2 = np.ix_(i0, i1, i2)
ind2 = (j0, slice(None), j2)
B1 = A[ind1]
B2 = A[ind2]
I would expect that B1 == B2, but actually, the shapes are different
>>> B1.shape
(2, 3, 2)
>>> B2.shape
(2, 1, 2, 3)
>>> B1
array([[[ 0, 2],
[ 3, 5],
[ 6, 8]],
[[ 9, 11],
[12, 14],
[15, 17]]])
>>> B2
array([[[[ 0, 3, 6],
[ 2, 5, 8]]],
[[[ 9, 12, 15],
[11, 14, 17]]]])
Someone understands why? Any idea of how I could get 'B1' by manipulating only 'A' and 'ind2' objects? The goal is that it would work for any nD arrays, and that I would not have to look for the shape of dimensions I want to keep entirely (hope I'm clear enough:)). Thanks!!
---EDIT---
To be clearer, I would like to have a function 'fun' such that
A[fun(ind2)] == B1
In restricted indexing cases like this using ix_
, it is possible to do the indexing in successive steps.
A[ind1]
is the same as
A[i1][:,i2][:,:,i3]
and since i2
is the full range,
A[i1][...,i3]
If you only have ind2
available
A[ind2[0].flatten()][[ind2[2].flatten()]
In more general contexts you have to know how j0,j1,j2
broadcast with each other, but when they are generated by ix_
, the relationship is simple.
I can imagine circumstances in which it would be convenient to assign A1 = A[i1]
, followed by a variety of actions involving A1
, including, but not limited to A1[...,i3]
. You have to be aware of when A1
is a view, and when it is a copy.
Another indexing tool is take
:
A.take(i0,axis=0).take(i2,axis=2)
这篇关于结合切片和广播的索引多维numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!