【问题标题】:comparing a string 1-d numpy array elementwise逐元素比较字符串一维numpy数组
【发布时间】:2016-05-16 18:42:03
【问题描述】:

我有两个包含字符串的一维数组(a 和 b),我想比较元素以获得输出 c,如下所示。我尝试将其转换为设置和比较,但这并没有给出正确的解决方案。 logical_xor 也不适用于字符串。我可以编写一个循环来执行此操作,但它违背了使用数组的目的,没有循环的最佳方法是什么?

  >>  a
      array(['S', 'S', 'D', 'S', 'N', 'S', 'A', 'S', 'M'], 
          dtype='|S1')
  >>  b
      array(['T', 'I', 'D', 'N', 'G', 'B', 'A', 'J', 'M'], 
          dtype='|S1')

  >> c 
     array([False, False, True, False, False, False, True, False, True], 
      dtype=bool)

【问题讨论】:

    标签: python arrays string numpy


    【解决方案1】:

    只需使用 ndarray 的 __eq__ 方法,即 ==

    >>> a = array(['S', 'S', 'D', 'S', 'N', 'S', 'A', 'S', 'M'], dtype='|S1')
    >>> b = array(['T', 'I', 'D', 'N', 'G', 'B', 'A', 'J', 'M'], dtype='|S1')
    >>> a == b
    array([False, False,  True, False, False, False,  True, False,  True], dtype=bool)
    

    【讨论】:

    • 啊!错过了最简单的选择...谢谢:)
    【解决方案2】:

    你可以使用numpy.equal

    import numpy as np
    c = np.equal(a,b)
    

    numpy.core.defchararray.equal

    c = np.core.defchararray.equal(a, b)
    

    编辑

    np.equal 一直是deprecated in the last numpy's releases,现在引发FutureWarning

    >>> c = np.equal(a,b)
    __main__:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
    >>> c
    NotImplemented
    

    相等运算符== 将遭受与np.equal 相同的命运。所以我建议使用:

    c = np.array([a == b], dtype=bool)
    

    【讨论】:

    • 这不起作用。你得到错误:FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison NotImplemented
    • 好的,这是对 numpy 的弃用(请参阅this stuff)。我编辑我的答案:)
    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 2016-06-30
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多