1

I want to add values from one array to another array after making some calculation, here I did it using for loop but I want efficient way doing so. Please help me.. thanx

from numpy import *
arr = array([1,2,3,4,5])
arr1 = []
for i in arr:
 arr1.append(i+5)
 
print(arr1)
nArray = array(arr1)
print(nArray)

Output :

[6, 7, 8, 9, 10]

[ 6 7 8 9 10]

Gilad Green
37.3k7 gold badges67 silver badges99 bronze badges
asked Nov 5, 2020 at 8:08
2
  • Simply do arr1 = arr + 5. Numpy broadcasting will take care of the rest. Commented Nov 5, 2020 at 8:10
  • Thanx Gilad Green Commented Nov 5, 2020 at 8:41

2 Answers 2

1

You should have just done:

nArray = arr + 5
answered Nov 5, 2020 at 8:10
Sign up to request clarification or add additional context in comments.

Comments

1

For a builtin Python list, you can use a list comprehension:

arr1 = [x + 5 for x in arr]

Since you are using a numpy array however, you can just add 5 to the array with:

arr1 = arr + 5

2 Comments

Remove the first part. It's correct but not efficient for numpy.
Thanx Thomas Saint

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.