This seems like it should be straightforward, but I'm stumped (also fairly new to numpy.)
I have a 1d array of integers a.
I want to generate a new 1d array b such that:
- the number of elements in b equals the sum of the elements in a
- The values in b are equal to some arbitrary constant divided by the corresponding element in a.
That's a mouthful, so here's an example of what I want to make it more concrete:
a = array([2,3,3,4])
CONSTANT = 120
.
.
.
b = array([60,60,
40,40,40,
40,40,40,
30,30,30,30])
Any help is appreciated!
CodePudding user response:
I think a pretty clear way to do this is
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)
CodePudding user response:
You can do this with np.concatenate
and good old fashioned 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.])