1

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!

1
  • so the number a[i] is the time you repeat and also the divisor? a = [1,2,3] -> b = [c/1, c/2,c/2 , c/3,c/3,c/3,] ? Commented Oct 28, 2021 at 0:07

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

This is a much better answer than mine. Nice one!
sorry I edited it so make it more clear and straightforward
Thank you both! Learned 2 new useful functions.
0

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

2 Comments

Perfect, Thank you!
@AlexParthemer I think you should prefer the other answer. That uses more idiomatic numpy which will probably be better optimized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.