【问题标题】:How to efficiently remove elements of one array from another如何有效地从另一个数组中删除一个数组的元素
【发布时间】:2020-12-04 03:48:09
【问题描述】:

我正在分析一个包含大约 135k 文档(每个文档有几页)和大约 800k 单词的词汇的文本语料库。我注意到有一半的词汇是频率为 1 或 2 的单词,所以我想删除它们。

所以我正在运行这样的东西:

remove_indices = np.array(index_df[index_df['frequency'] <= 2]['index']).astype(int)

for file_name in tqdm(corpus):
    content = corpus[file_name].astype(int)
    content = [index for index in content if index not in remove_indices]
    corpus[file_name] = np.array(content).astype(np.uint32)

corpus 看起来像这样:

{
    'filename1.txt': np.array([43, 177718, 3817, ...., 28181]).astype(np.uint32),
    'filename2.txt': ....
}

并且每个单词之前都被编码为一个正整数索引。

问题在于content = [index for index in content if index not in remove_indices] 每次迭代都需要经过len(remove_indices) * len(content) 的检查次数。这需要很长时间(tqdm 告诉我 100h+)。有关如何加快速度的任何提示?

到目前为止我所做的尝试

  • 利用如果单词只有频率 1 或 2,我们可以在将其从语料库中删除后将其从 remove_indices 中删除。仍然需要永远...

【问题讨论】:

    标签: python nlp data-analysis


    【解决方案1】:

    您可以在@ 987654324 https://numpy.org/devdocs/reference/generated/numpy.isin.html而不是此列表的理解。

    或者,您可以创建现有单词/索引的set。那么这个in 操作将是 O(1) 而不是 O(n)(其中 n 是数组的长度)。

    【讨论】:

    猜你喜欢
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多