简体   繁体   English

在不循环的情况下访问 3D numpy 数组中的多列

[英]Access multiple columns in a 3D numpy array without looping

I have a large 3D array A with shape (N, M, L) .我有一个形状为(N, M, L)的大型 3D 阵列A

I have a list of coordinates of columns I want to access stored in a 2D array B :我有一个列的坐标列表,我想访问存储在二维数组B

[[i1 j1]
 [i2 j2]
 [i3 j3]
 ....   ]

I have something that works OK but involves looping over B and accessing A multiple times.我有一些工作正常但涉及循环B并多次访问A Is there a way to avoid this using slicing or another method?有没有办法使用切片或其他方法来避免这种情况?

My code so far:到目前为止我的代码:

data_out = []
for p in B:
    i, j = p
    col = A[:, i, j]
    data_out.append(col)

Use fancy indexing:使用花哨的索引:

A[(slice(None), *B.T)].T

The explicit parentheses are necessary to use star expansion, which means that you have to write out : explicitly as slice(None) .显式括号是使用星型扩展所必需的,这意味着您必须明确写出:slice(None) You can also do你也可以这样做

A[:, B[:, 0], B[:, 1]].T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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