繁体   English   中英

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

[英]Numpy: Create new array from 1d integer array where each element in integer array represents the number of elements in the new array

这看起来应该很简单,但我很难过(对 numpy 来说也很新。)

我有一个一维整数数组a

我想生成一个新的一维数组b使得:

  • b中的元素的数量等于所述元素的总和
  • B中的值等于由相应的元件分开的一些任意的常数。

这是一口,所以这里有一个我想让它更具体的例子:

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.])

暂无
暂无

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

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