python - 使用 2 维数组切片 3 维数组

标签 python arrays numpy

假设我们有两个矩阵:

x = np.random.randint(10, size=(2, 3, 3))
idx = np.random.randint(3, size=(2, 3))

问题是使用idx访问x的元素,方式如下:

dim1 = x[0, range(0,3), idx[0]]  # slicing x[0] using idx[0]
dim2 = x[1, range(0,3), idx[1]]
res = np.vstack((dim1, dim2))

有什么巧妙的方法可以做到这一点吗?

最佳答案

您可以将其索引为 basic way ,只是索引器数组的大小必须匹配。这就是那些 .reshape 的用途:

x[np.array([0,1]).reshape(idx.shape[0], -1), 
  np.array([0,1,2]).reshape(-1,idx.shape[1]),
  idx]
Out[29]: 
array([[ 0.10786251,  0.2527514 ,  0.11305823],
       [ 0.67264076,  0.80958292,  0.07703623]])

关于python - 使用 2 维数组切片 3 维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323054/

相关文章:

python - CX_Oracle - 将数据从 Oracle 导入到 Pandas 数据框

android - 如何在不转换为位图的情况下裁剪包含 Y'(亮度)的 byte[] 数组

ios - 如何在 Objective c 的 UITableview 中获取 NSMutableArray 的实际值而不是索引

python - Python 中来自值列表的加权随机数

python - 在 NumPy 中创建随机 float 和 float64 数组

python - 这是访问与 Python 脚本相邻/打包的数据的批准方式吗?

python - 类型错误 : 'NoneType' object has no attribute '__getitem__15'

python - Pandas : adding a column to pivot and filtering

c++:检查对象数组中类的对象

python - numpy中楼层划分的奇怪结果