0

I would like to build array based on another two array using numpy, your help much appreciated.

import numpy as np
array1 = np.arange(1, 5 + 1, 1)
array2 = np.arange(1, 2 + 1, 1)

print('array1 ==>', array1)
print('array2 ==>', array2)

Output:

array1 ==> [1 2 3 4 5]
array2 ==> [1 2]
output_array ==> [ 1.1  1.2  2.1  2.2  3.1  3.2  4.1  4.2]
4
  • output_array = np.array([i + x/10 for i in array1 for x in array2]) Commented Aug 27, 2020 at 2:54
  • 1
    Numpy broadcasting: (array1[:, None] + array2 / 10).ravel() Commented Aug 27, 2020 at 2:55
  • Why is there no 5.1 and 5.2 in your example output? what is the pattern? it is unclear what you would want the output to be in case of numbers larger than 10 too. Please elaborate so we can help better. Thank you Commented Aug 27, 2020 at 7:02
  • @Psidom there's the broadcasting magic I was looking for! Nice Commented Aug 28, 2020 at 1:11

1 Answer 1

1

Here's a list comprehension that will get the job done:

array1 = [1, 2, 3, 4, 5]
array2 = [1, 2]
output_array = [i + 0.1*j for i in array1 for j in array2]
print(output_array)  
# prints [1.1, 1.2, 2.1, 2.2, 3.1, 3.2, 4.1, 4.2, 5.1, 5.2]

There may be some clever bit of broadcasting magic that will let you do this with numpy calls in an extremely performant way, but here's a very simple way:

array1 = [1, 2, 3, 4, 5]
array2 = [1, 2]
output_array = np.repeat(array1, 2) + np.tile(array2, 5)*0.1
print(output_array)  
# prints [1.1, 1.2, 2.1, 2.2, 3.1, 3.2, 4.1, 4.2, 5.1, 5.2]

Personally I prefer the list comprehension approach, it's cleaner and probably faster

edit: From another person's comment, here's a sweet broadcasting approach:

output_array = (array1[:, None] + array2 / 10).ravel() 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the response, if array2 values goes beyond 10 above steps not working. Example array2 = [ 1 2 3 4 5 6 7 8 9 10 11]
Looping is probably slower than broadcasting for large arrays. And cleanness is somewhat subjective. Broadcasting in my opinion is neater.
@Tech what is your expected output in case of that example?
@Tech all 3 solutions work for me when array2 has a size of 15 or 20. The second solution needs to use the size of the respective arrays, that may be where you're running into the problem. I recommend just using the 3rd approach though, which is the simplest

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.