我有一个 numpy 字符串数组,其中一些是重复的,我想将每个元素与其他每个元素进行比较,以生成一个由 1 和 0 组成的新向量,指示每对是否 (i,j)
相同或不同。
例如["a","b","a","c"]
-> 12 元素 (4*3) 向量 [1, 0, 1, 0, 0, 1 , 0, 0, 1, 0, 1, 0, 0, 0, 0, 1]
有没有一种方法可以在 numpy 中快速完成此操作,而无需对所有元素对进行双循环?我的数组有大约 240,000 个元素,因此以简单的方式完成它需要非常长的时间。
我知道numpy.equal.outer
,但显然numpy.equal
没有在字符串上实现,所以看来我需要一些更聪明的东西比较它们的方法。
最佳答案
构建一个包含字符串哈希(使用内置 hash()
函数)值的数组。
eg = ['a', 'b', 'c', 'a']
hashed = np.array([hash(s) for s in eg])
result = np.equal.outer(hashed, hashed)
输出:
[[ True False False True]
[False True False False]
[False False True False]
[ True False False True]]
如果只有 1 个字符长的字符串,可以使用 ord()
代替 hash()
:
Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224.
关于python - 将 np 字符串数组中的每个元素与其他元素进行比较的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42724795/