Python 基于另一个数组在Numpy数组中设置值 1term\u map跟踪哪个术语位于哪个位置。 2term_分数跟踪每个位置每个术语的权重。 3获得唯一值和反向索引。 4计算唯一值的分数。 5初始化要更新的数组。索引对应于术语映射变量中的值。 6所需:将3中列出的位置对应的值4插入vocab变量。
如何创建6Python 基于另一个数组在Numpy数组中设置值 1term\u map跟踪哪个术语位于哪个位置。 2term_分数跟踪每个位置每个术语的权重。 3获得唯一值和反向索引。 4计算唯一值的分数。 5初始化要更新的数组。索引对应于术语映射变量中的值。 6所需:将3中列出的位置对应的值4插入vocab变量。,python,arrays,numpy,Python,Arrays,Numpy,如何创建6 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
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.]
事实证明,我们可以通过将term\u映射
和term\u得分
输入到np.bincount
中,避免使用np.unique
步骤直接获得所需的输出,还可以使用可选参数minlength
提及输出数组的长度
因此,我们可以简单地做到-
final_output = np.bincount(term_map, term_scores, minlength=13)
样本运行-
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.])
那么,问题是?@Divakar,我想他无法完成第六阶段。是的@TonyTannous,没错。很抱歉没有说得更清楚。考虑到前面提到的5个更难的障碍,我认为这是微不足道的。如果可能的话,我不想使用for循环。这很接近-
In [262]: value_sums = np.bincount(idx, term_scores)
In [263]: value_sums
Out[263]: array([ 4., 16., 9., 21.])
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.])
In [255]: updated_vocab
Out[255]: 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)
final_output = np.bincount(term_map, term_scores, minlength=13)
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.])