Reputation: 51
I have an array of ten random values generated using Numpy. I want to perform an operation on each element in the array by looping over all ten elements and then add the result of each to a new array. The first part of looping over the array but I am stuck on how to add the result to a new array.
So far I have tried something along the lines of:
import numpy as np
array = np.random.rand(10)
empty_array = np.zeros(10)
for elem in array:
new_val = elem**2
where empty_array is an array of 10 elements set to zero, my logic being similar to initialising an empty list to add elements to when looping over another list or array. I am stuck on how to replace the corresponding elements of empty_array with the square of elements in 'array'.
Any help on how to do this or a better way of doing this would be greatly appreciated!
Upvotes: 0
Views: 1860
Reputation: 799
This is a case where NumPy vectorisation comes in quite handy:
import numpy as np
array = np.random.rand(10)
array2 = array*array
And if you were dead set on calculating things in a loop (which I wouldn't recommend, but each to their own), you would add the new value to empty_array like this:
import numpy as np
array = np.random.rand(10)
empty_array = np.zeros(10)
for i in range(array.shape[0]):
# Get element and calculate square.
# Note that using elem**2 is in some cases less efficient than using elem*elem.
elem = array[i]
new_val = elem**2
empty_array[i] = new_val
Upvotes: 0
Reputation: 530930
One of the reasons to use Numpy is its expressiveness for cases like these.
>>> import numpy as np
>>> a = np.random.rand(10)
>>> a
array([0.94797029, 0.39628409, 0.64609633, 0.44994779, 0.23083464,
0.60191075, 0.71651581, 0.78152364, 0.05516691, 0.22452054])
>>> a **2
array([0.89864768, 0.15704108, 0.41744046, 0.20245301, 0.05328463,
0.36229656, 0.5133949 , 0.6107792 , 0.00304339, 0.05040947])
You don't have to iterate over the original array and build up the new array step by step: you just "square" the array itself.
Upvotes: 2
Reputation: 369
You can append the new value like:
import numpy as np
array = np.random.rand(10)
new_array = []
for elem in array:
new_array.append(elem ** 2)
Or using the list comprehension:
import numpy as np
array = np.random.rand(10)
new_array = [e**2 for e in array]
Upvotes: 0