Py学习  »  Python

python:从3d numpy数组中的2d数组访问保存的点

Sev • 4 年前 • 742 次点击  

我有一个二维核阵列 (shape(y,x)=601,1200) 以及一个3d numpy阵列 (shape(z,y,x)=137,601,1200) .

在我的二维数组中,我保存了 z 价值观 y, x 我现在想从我的3d数组中访问的点,并将其保存到一个新的2d数组中。

我试过这样的方法但没有成功。

levels = array2d.reshape(-1)
y = np.arange(601)
x = np.arange(1200)
newArray2d=oldArray3d[levels,y,x]

索引器错误:形状不匹配:索引数组无法与形状(721200,)(601,)(1200,)一起广播

我不想尝试使用循环的方法,有没有更快的方法?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/42981
 
742 次点击  
文章 [ 2 ]  |  最新文章 4 年前
hpaulj
Reply   •   1 楼
hpaulj    5 年前

你的问题有些含糊,但我认为你想这样做:

In [2]: arr = np.arange(24).reshape(4,3,2)                                      
In [3]: levels = np.random.randint(0,4,(3,2))                                   
In [4]: levels                                                                  
Out[4]: 
array([[1, 2],
       [3, 1],
       [0, 2]])
In [5]: arr                                                                     
Out[5]: 
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]]])
In [6]: arr[levels, np.arange(3)[:,None], np.arange(2)]                         
Out[6]: 
array([[ 6, 13],
       [20,  9],
       [ 4, 17]])

levels IS(3,2)。我创建了另外两个索引数组,它们用它(3,1)和(2,)广播。结果是一个(3,2)数组 arr ,由它们的组合索引选择。

fountainhead
Reply   •   2 楼
fountainhead    5 年前

这是您拥有的数据:

x_len = 12     # In your case, 1200
y_len = 6      # In your case, 601
z_len = 3      # In your case, 137

import numpy as np
my2d = np.random.randint(0,z_len,(y_len,x_len))
my3d = np.random.randint(0,5,(z_len,y_len,x_len))

这是构建新二维阵列的一种方法:

yindices,xindices = np.indices(my2d.shape)
new2d = my3d[my2d[:], yindices, xindices]

笔记:

  1. 我们正在使用整数高级索引。
  2. 这意味着我们为三维数组编制索引 my3d 有3个整数索引数组。
  3. 有关整数数组索引工作原理的详细说明,请参阅 my answer on this other question
  4. 在你的尝试中,没有必要用 reshape(-1) ,因为我们传递的整数索引数组的形状(在任何广播之后)将成为结果2d数组的形状。
  5. 另外,在您的尝试中,第二个和第三个索引数组需要具有相反的方向。也就是说,它们一定是有形状的 (y_len,1) (1, x_len) . 注意 1 . 这确保了这两个索引数组将被广播