用另一个数组切片多维数组
编辑了一个更清晰的示例,并包含了解决方案
我想对任意维数组进行切片,其中我固定前n
维并保留其余维。此外,我希望能够将 n
固定尺寸存储在变量中。例如,
Q = np.arange(24).reshape(2, 3, 4) # array to be sliced
# array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
Q[0, 1, ...] # this is what I want manually
# array([4, 5, 6, 7])
# but programmatically:
s = np.array([0, 1])
Q[s, ...] # this doesn't do what I want: it uses both s[0] and s[1] along the 0th dimension of Q
# array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
np.take(Q, s) # this unravels the indices and takes the s[i]th elements of Q
# array([0, 1])
Q[tuple(s)] # this works! Thank you kwin
# array([4, 5, 6, 7])
有没有一种干净的方法可以做到这一点?
edited with a clearer example, and included solution
I'd like to slice an arbitrary dimensional array, where I pin the first n
dimensions and keep the remaining dimensions. In addition, I'd like to be able to store the n
pinning dimensions in a variable. For example
Q = np.arange(24).reshape(2, 3, 4) # array to be sliced
# array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
Q[0, 1, ...] # this is what I want manually
# array([4, 5, 6, 7])
# but programmatically:
s = np.array([0, 1])
Q[s, ...] # this doesn't do what I want: it uses both s[0] and s[1] along the 0th dimension of Q
# array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]],
# [[12, 13, 14, 15],
# [16, 17, 18, 19],
# [20, 21, 22, 23]]])
np.take(Q, s) # this unravels the indices and takes the s[i]th elements of Q
# array([0, 1])
Q[tuple(s)] # this works! Thank you kwin
# array([4, 5, 6, 7])
Is there a clean way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以做到这一点:
或以下:
这两个收益率
数组([0.58383736,0.80486868])
。恐怕我对
s
的元组版本与用s
本身的索引的工作方式不同。我直观地尝试的另一件事是q [*s]
,但这是语法错误。You could do this:
Or this:
Both of these yield
array([0.58383736, 0.80486868])
.I'm afraid I don't have a great intuition for exactly why the tuple version of
s
works differently from indexing withs
itself. The other thing I intuitively tried isQ[*s]
but that's a syntax error.我不确定你想要什么输出,但你可以做几件事。
如果您希望输出如下所示:
Q[list(s)]
应该可以。np.array([Q[i] for i in s])
也有效。如果您希望输出如下所示:
那么正如 @kwinkunks 提到的,您可以使用 Q[tuple(s)] 或 np.take(Q, s)
I am not sure what output you want but there are several things you can do.
If you want the output to be like this:
Q[list(s)]
should work.np.array([Q[i] for i in s])
also works.If you want the output to be like this:
Then as @kwinkunks mentioned you could use
Q[tuple(s)]
ornp.take(Q, s)