我有一个名单,比如:
names = ['A', 'B', 'C', 'D']
以及文档列表,在每个文档中都会提到其中的一些名称。
document =[['A', 'B'], ['C', 'B', 'K'],['A', 'B', 'C', 'D', 'Z']]
我想得到一个作为共现矩阵的输出,比如:
A B C D
A 0 2 1 1
B 2 0 2 1
C 1 2 0 1
D 1 1 1 0
在R中有一个解决这个问题的方法(Creating co-occurrence matrix),但是我在Python中做不到。我想在熊猫身上做,但没有进展!
输出
另一种选择是使用构造函数
csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
来自scipy.sparse.csr_matrix,其中data
、row_ind
和col_ind
满足 关系a[row_ind[k], col_ind[k]] = data[k]
。诀窍是通过遍历文档并创建元组列表(doc-id,word-id)来生成
row_ind
和col_ind
。data
只是一个长度相同的向量。将文档单词矩阵与其转置相乘将得到共现矩阵。
此外,这在运行时间和内存使用方面都是有效的,因此它还应该处理大的小体。
运行示例:
输出:
显然,这可以扩展到您的目的,但它执行一般操作时要记住:
相关问题 更多 >
编程相关推荐