Python Numpy按索引列表调用数组值

Python Numpy按索引列表调用数组值,python,numpy,Python,Numpy,我有一个2D值数组,我想用两个索引列表x,y来调用它。它以前工作得很好,我不知道为什么现在不工作,可能是python版本,不确定 x = np.squeeze(np.where(data['info'][:,2]==cdp)[0]) y = np.squeeze(np.where((data['Time']>=ub) & (data['Time']<=lb))[0]) s = data['gather'][x,y] 我不知道是什么问题。当我分两个阶段做的时候,它就工作了

我有一个2D值数组,我想用两个索引列表x,y来调用它。它以前工作得很好,我不知道为什么现在不工作,可能是python版本,不确定

x = np.squeeze(np.where(data['info'][:,2]==cdp)[0])
y = np.squeeze(np.where((data['Time']>=ub) & (data['Time']<=lb))[0])

s = data['gather'][x,y]
我不知道是什么问题。当我分两个阶段做的时候,它就工作了

s = data['gather'][:,y]; s = s[x,:]
但是,我不能这样做,我需要一次跑步

In [92]: data = np.arange(12).reshape(3,4)                                                                           
In [93]: x,y = np.arange(3), np.arange(4)                                                                            
In [94]: data[x,y]                                                                                                   
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-94-8bd18da6c0ef> in <module>
----> 1 data[x,y]

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (4,) 
MATLAB等效程序需要一个额外的函数“Indexes to sub”或类似的名称

两阶段索引:

In [95]: data[:,y][x,:]                                                                                              
Out[95]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
ix
是一个方便的工具,用于构建块访问索引:

In [96]: data[np.ix_(x,y)]                                                                                           
Out[96]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
注意它产生了什么:

In [97]: np.ix_(x,y)                                                                                                 
Out[97]: 
(array([[0],
        [1],
        [2]]), array([[0, 1, 2, 3]]))
这与执行以下操作相同:

In [98]: data[x[:,None], y]                                                                                          
Out[98]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

x[:,无]
is(3,1),
y
is(4,);它们进行广播以产生(3,4)个选择。

您可以简单地尝试
数据['gather'][:,y][x,:]
?您不能将两个不一起广播的数组编入索引。重新阅读文档的
高级索引
部分。MATLAB和numpy在处理块索引的方式上是不同的
x[[0,1,2],[0,1,2]
选择对角线,而不是(3,3)块。@NikP的方法应该是正确的。
数据是什么?字典?数据帧?
In [97]: np.ix_(x,y)                                                                                                 
Out[97]: 
(array([[0],
        [1],
        [2]]), array([[0, 1, 2, 3]]))
In [98]: data[x[:,None], y]                                                                                          
Out[98]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])