python - 将 np 字符串数组中的每个元素与其他元素进行比较的最快方法

标签 python numpy numpy-ufunc

我有一个 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/

相关文章:

python - pandas.read_csv 来自字符串或包数据

python - 我是否正确使用 scipy.linalg.solve_discrete_lyapunov

python - 相当于 tensorflow 中的 np.add.at

python - ufunc 与 Numpy 中的基本算术运算符

python - Python 中实时信号的心电图数据分析

python - 在python中使用random.random生成随机样本

python - 如何安装 django-utils?

python - Tkinter 网格填充空白空间

python - 如何根据条件为每个 id 分配二进制值

python - 使用 numpy ufuncs 就地修改 Pandas 数据框