简体   繁体   English

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

[英]Set Values in Numpy Array Based Upon Another Array

1 term_map tracks which term is in which position. 1 term_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])

2 term_scores tracks the weight of each term at each position. 2 term_scores跟踪每个位置上每个术语的权重。

In [258]: term_scores = np.array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])

In [259]: term_scores
Out[259]: array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])

3 Get the unique values and the inverse indices. 3获取唯一值和反索引。

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

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

4 Compute the scores for the unique values. 4计算唯一值的分数。

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

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

5 Initialize Array To Update. 5初始化要更新的阵列。 The indices correspond to the values in the term_map variable. 索引对应于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 DESIRED: Insert the values 4 corresponding to the positions listed in 3 into the vocab variable. 6期望:将与3中列出的位置相对应的值4插入vocab变量中。

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

How do I create 6? 如何创建6?

As it turns out, we can avoid the np.unique step to directly get to the desired output by feeding in term_map and term_scores to np.bincount and also mention the length of the output array with its optional argument minlength . 事实证明,我们能够避免np.unique步骤,通过在进料直接得到所需的输出term_mapterm_scoresnp.bincount并且还提到与它的可选参数的输出阵列的长度minlength

Thus, we could simply do - 因此,我们可以简单地-

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

Sample run - 样品运行-

In [142]: 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])
     ...: 

In [143]: np.bincount(term_map, term_scores, minlength=13)
Out[143]: 
array([  4.,   0.,  16.,   9.,  21.,   0.,   0.,   0.,   0.,   0.,   0.,
         0.,   0.])
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)

OUT: [ 4. 0. 16. 9. 21. 0. 0. 0. 0. 0. 0. 0. 0.] OUT: [ 4. 0. 16. 9. 21. 0. 0. 0. 0. 0. 0. 0. 0.]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM