【问题标题】:about python matrix logical indexing关于python矩阵逻辑索引
【发布时间】:2017-12-28 14:14:22
【问题描述】:

我是python新手,看不懂下面的代码; 我希望 test1 和 test2 给我相同的结果(8,第二行的总和),而不是

a=np.matrix([[1,2,3],[1,3, 4]])
b=np.matrix([[0,1]])
print(np.where(b==1))
test1=a[np.nonzero(b==1),:]
print(test1.sum())
ind,_=np.nonzero(b==1);  #found in a code that I'm trying to undestand (why the _ ?)

test2=a[ind,:]
print(test2.sum())

给我

 (array([0]), array([1]))
 14
 6

在第一种情况下,我有整个矩阵的总和,在第二种情况下,我有第一行的总和(而不是第二行)

我不明白为什么会出现这种行为

【问题讨论】:

  • nonzero 返回一个元组,因此在第一种情况下,您使用元组进行切片。在第二个示例中,_ 用作一次性/占位符变量(您将在 SO 上找到有关该问题的答案),因此您仅使用 nonzero 返回的元组的第一个元素进行切片,因此在结果

标签: python numpy matrix indexing


【解决方案1】:
In [869]: a
Out[869]: 
matrix([[1, 2, 3],
        [1, 3, 4]])
In [870]: b
Out[870]: matrix([[0, 1]])

在此使用wherenonzero 相同:

In [871]: np.where(b==1)
Out[871]: (array([0], dtype=int32), array([1], dtype=int32))
In [872]: np.nonzero(b==1)
Out[872]: (array([0], dtype=int32), array([1], dtype=int32))

它给出一个元组,每个维度都有一个索引数组(np.matrix 为 2)。 ind,_= 只是解包这些数组,然后扔掉第二个。 _ 在交互式会话中重复使用,例如我正在使用的会话。

In [873]: ind,_ =np.nonzero(b==1)
In [874]: ind
Out[874]: array([0], dtype=int32)

使用where 选择会返回来自a 的(0,1) 值。但这就是你想要的吗?

In [875]: a[np.where(b==1)]
Out[875]: matrix([[2]])

添加: 确实索引整个数组,但增加了维度;再次可能不是我们想要的

In [876]: a[np.where(b==1),:]
Out[876]: 
matrix([[[1, 2, 3]],

        [[1, 3, 4]]])

ind 是单个索引数组,因此从a 中选择 0 的行。

In [877]: a[ind,:]
Out[877]: matrix([[1, 2, 3]])
In [878]: 

但是b==1是否应该找到b的第二个元素,然后选择a的第二行?为此,我们必须使用来自where 的第二个索引数组:

In [878]: a[np.where(b==1)[1],:]
Out[878]: matrix([[1, 3, 4]])

或者a的第2列对应b的第2列

In [881]: a[:,np.where(b==1)[1]]
Out[881]: 
matrix([[2],
        [3]])

因为abnp.matrix,所以索引结果总是2d。

对于c 数组,where 生成单个元素元组

In [882]: c=np.array([0,1])
In [883]: np.where(c==1)
Out[883]: (array([1], dtype=int32),)
In [884]: a[_,:]                # here _ is the last result, Out[883]
Out[884]: matrix([[1, 3, 4]])

我们通常建议使用np.array 来构造新数组,甚至是二维数组。 np.matrix 为任性的 MATLAB 用户提供了便利,却常常让 numpy 新用户感到困惑。

【讨论】:

    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2012-07-10
    • 1970-01-01
    • 2016-08-11
    • 2023-03-04
    • 2021-11-30
    相关资源
    最近更新 更多