python - 您可以从 numpy 数组或 pandas 数据帧中提取超过阈值的数据索引吗
问题描述
我正在使用以下内容来比较几个字符串。这是我能设计出的最快的方法,但它会产生一个非常大的二维数组。我可以看看,看看我想要什么。理想情况下,我想设置一个阈值并将每个值的索引拉到该数字之上。更复杂的是,我不希望索引将字符串与其自身进行比较,并且字符串可能会在其他地方重复,所以我想知道是否是这种情况,所以我不能只忽略 1。
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
texts = sql.get_corpus()
vectorizer = TfidfVectorizer()
vectors = vectorizer.fit_transform(texts)
similarity = cosine_similarity(vectors)
sql.get_corups()
返回一个字符串列表,目前有 1600 个字符串。
我想要的可能吗?我尝试使用 Levenshtein 将每个 1.4M 组合相互比较,这很有效,但它需要 2.5 小时而不是以上的一半。我也尝试过 spacy 的 vecotrs,这需要几天时间。
解决方案
我不完全确定我是否正确阅读了您的帖子,但我相信这应该可以帮助您入门:
import numpy as np
# randomly distributed data we want to filter
data = np.random.rand(5, 5)
# get index of all values above a threshold
threshold = 0.5
above_threshold = data > threshold
# I am assuming your matrix has all string comparisons to
# itself on the diagonal
not_ident = np.identity(5) == 0.
# [edit: to prevent duplicate comparisons, use this instead of not_ident]
#upper_only = np.triu(np.ones((5,5)) - np.identity(5))
# 2D array, True when criteria met
result = above_threshold * not_ident
print(result)
# original shape, but 0 in place of all values not matching above criteria
values_orig_shape = data * result
print(values_orig_shape)
# all values that meet criteria, as a 1D array
values = data[result]
print(values)
# indices of all values that meet criteria (in same order as values array)
indices = [index for index,value in np.ndenumerate(result) if value]
print(indices)
推荐阅读
- api - 错误 401 未经授权与 Marvel API 连接
- java - 通过使用安全的 Args 导航,Bundle 变为空
- hadoop - 直接使用 scp 将 hdfs 文件复制到远程 linux 服务器?
- php - 如何在 Laravel 的搜索表单中将获取参数作为漂亮的 URL 发送?
- r - 使用 R (RPostgreSQL) 连接到 Google Cloud SQL postgresql 时出现问题
- c# - 如何让我的linkedIn 共享网址正常工作
- python - 当有人解释代码时,“L”是什么意思?
- android - onSuccessTask 与 addOnSuccessListener?
- jenkins - 如何使用布尔参数作为构建参数来复制工件?
- excel - 数据名中带有空格的连接字符串 vba 被破坏