Numpy:从一维整数数组中创建新数组,其中整数数组中的每个元素表示新数组中的元素个数



这看起来应该是直截了当的,但我被难住了(对numpy也相当陌生)

我有一个一维整数数组a

我想生成一个新的1d数组b这样:

  • b中的元素个数等于a
  • 中的元素个数之和。b中的值等于任意常数除以a中的相应元素。

这太长了,所以这里有一个我想让它更具体的例子:

a = array([2,3,3,4])
CONSTANT = 120
.
.
.
b = array([60,60,
40,40,40,
40,40,40,
30,30,30,30])

任何帮助都是感激的!

我认为一个很明确的方法是

import numpy as np
a = np.array([2,3,3,4]) 
constant = 120
#numpy.repeat(x,t) repeats the val x t times you can use x and t as vectors of same len
b = np.repeat(constant/a , a)

您可以使用np.concatenate和老式的zip:

>>> elements = CONSTANT / a
>>> np.concatenate([np.array([e]*n) for e, n in zip(elements, a)])
array([60., 60., 40., 40., 40., 40., 40., 40., 30., 30., 30., 30.])

最新更新