【问题标题】:How to make this kind of equality array fast (in numpy)?如何使这种相等数组快速(在 numpy 中)?
【发布时间】:2011-12-02 13:06:56
【问题描述】:

我有两个 numpy 数组(二维),例如

a1 = array([["a","b"],["a","c"],["b","b"],["a","b"]])
a2 = array([["a","b"],["b","b"],["c","a"],["a","c"]])

获得这样一个矩阵的最优雅的方法是什么:

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

如果 all(a1[i,:] == a2[j,:]) 则元素 (i,j) 为 1,否则为 0

(所有涉及两个 for 循环的东西我都觉得不优雅)

【问题讨论】:

    标签: python numpy


    【解决方案1】:
    >>> (a1[:,numpy.newaxis] == a2).all(axis=2)
    array([[ True, False, False, False],
           [False, False, False,  True],
           [False,  True, False, False],
           [ True, False, False, False]], dtype=bool)
    

    如果你真的需要整数,最后一步转换为int

    >>> (a1[:,numpy.newaxis] == a2).all(axis=2).astype(int)
    array([[1, 0, 0, 0],
           [0, 0, 0, 1],
           [0, 1, 0, 0],
           [1, 0, 0, 0]])
    

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2012-11-15
      • 2020-07-20
      • 1970-01-01
      • 2010-12-25
      • 2019-07-09
      • 1970-01-01
      • 2014-05-23
      • 2015-12-12
      相关资源
      最近更新 更多