【问题标题】:Multiply by the factor the number of times that the position appears in the array (Python)乘以该位置在数组中出现的次数(Python)
【发布时间】:2021-05-14 01:46:23
【问题描述】:

我正在尝试使用“pythonic”方式或使用库(除了“for”循环之外的任何东西)

my_array = np.array([2,4,6])
my_array[[0,2,0]] = my_array[[0,2,0]] * 2

预期结果:

[8,4,12]

但是,我得到:

[4,4,12]

这对我不起作用,因为如果通过索引,0 位置重复 n 次,我需要将位置 0 的因子 (2) 乘以两倍。

不能使用“For”循环,因为有数十亿个数据点

【问题讨论】:

    标签: python arrays list numpy pytorch


    【解决方案1】:

    你可以试试:

    >>> num_occurrences_list = [0,2,0]
    >>> factor = 2
    >>> my_array * np.power(factor, np.bincount(num_occurrences_list))
    array([ 8,  4, 12])
    

    但我不确定它是否比显式使用 for 循环提供任何优势。

    这里,np.bincount 提供了一个数组,其中每个索引都包含它在列表中出现的次数。 np.power 以 2 为底数指定您希望乘以 2 的次数。最后,您将计算出的权重与数组中每个元素的实际相乘。

    【讨论】:

    • 谢谢!它工作得很好,提高了我的表演时间! :D
    猜你喜欢
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多