基于另一个数组在Numpy数组中设定值

2024-09-30 18:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

1term_map跟踪哪个术语处于哪个位置。

In [256]: term_map = np.array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])

In [257]: term_map
Out[257]: array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])

2term_scores跟踪每个项在每个位置的权重。

^{pr2}$

3得到唯一值和逆指数。

In [260]: unqID, idx = np.unique(term_map, return_inverse=True)

In [261]: unqID
Out[261]: array([0, 2, 3, 4])

4计算唯一值的得分。

In [262]: value_sums = np.bincount(idx, term_scores)

In [263]: value_sums
Out[263]: array([  4.,  16.,   9.,  21.])

5初始化要更新的数组。索引对应于term_map变量中的值。

In [254]: vocab = np.zeros(13)

In [255]: vocab
Out[255]: array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

6所需:将对应于3中所列位置的值4插入vocab变量。

In [255]: updated_vocab
Out[255]: array([ 4.,  0.,  16.,  9.,  21.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

如何创建6?在


Tags: inmapvaluenpoutarray权重术语
2条回答
import numpy as np

term_map = np.array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])
term_scores = np.array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])
unqID, idx = np.unique(term_map, return_inverse=True)
value_sums = np.bincount(idx, term_scores)

vocab = np.zeros(13)
vocab[unqID] = value_sums
print(vocab)

输出:[ 4. 0. 16. 9. 21. 0. 0. 0. 0. 0. 0. 0. 0.]

事实证明,我们可以通过输入term_mapterm_scores来避免{}步骤直接获得所需的输出,并且还可以使用可选参数minlength提到输出数组的长度。在

因此,我们可以简单地做-

final_output = np.bincount(term_map, term_scores, minlength=13)

样本运行-

^{pr2}$

相关问题 更多 >