按元素比较字符串1-d numpy数组 [英] comparing a string 1-d numpy array elementwise
本文介绍了按元素比较字符串1-d numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个包含字符串的1-d数组(a和b),我想按元素进行比较以获取输出c,如下所示.我尝试将其转换为设置值并进行比较,但是并没有给出正确的解决方案.同样,logical_xor不适用于字符串.我可以编写一个循环来执行此操作,但是这样做却违背了使用数组的目的,没有循环的最佳方法是什么?
I have two 1-d arrays (a and b) containing strings, which I want to compare element wise to get output c like shown below. I tried converting it to set and comparing, however that does not give the correct solution. Also logical_xor does not work for string. I can write a loop to do this but then it defeats the purpose of using arrays, What can be the best way to do this without a loop?
>> 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)
推荐答案
只需使用ndarray的__eq__方法,即==
Just use the ndarray's __eq__ method, i.e. ==
>>> 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)
这篇关于按元素比较字符串1-d numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文