【问题标题】:Set Values in Numpy Array Based Upon Another Array基于另一个数组在 Numpy 数组中设置值
【发布时间】:2017-07-06 01:58:30
【问题描述】:

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 跟踪每个词条在每个位置的权重。

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 获取唯一值和反向索引。

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 DESIRED:将与 3 中列出的位置对应的值 4 插入到 vocab 变量中。

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

如何创建 6?

【问题讨论】:

  • 那么,问题是?
  • @Divakar 我猜他无法完成第 6 阶段。
  • 是的@TonyTannous,这是正确的。抱歉没有说得更清楚。
  • 我认为这是微不足道的,因为在此之前涵盖了 5 个更困难的障碍。
  • 如果可能,我不想使用 for 循环。这非常接近 - stackoverflow.com/questions/8373079/…

标签: python arrays numpy


【解决方案1】:

事实证明,我们可以通过将term_mapterm_scores 输入到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.])

【讨论】:

    【解决方案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.]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多