1

Consider this simple problem: in a list of integers I need multiply all even number by 10. I can certainly do element-wise operation such as:

[if x%2==0: x=x*10 for x in arr]

But what if I the operation has to be operated on the array level? The trouble I am having is after the operation on the filtered array, how do I nicely put them back to the original array?

Code example:

arr=np.arange(1,10) # the original array array([1, 2, 3, 4, 5, 6, 7, 8, 9])
filter1 = arr%2==0  # the filter 
arr1=arr[filter1]   # the filtered array array([2, 4, 6, 8])
arr1=arr1*10        # the 'array'-wise operation array([20, 40, 60, 80])


# this is the part I am trying to improve
i=0
j=0
arr2=[]
for f in filter1:
    if f:
        arr2.append(arr1[i])
        i=i+1
    else:
        arr2.append(arr[j])
    j=j+1

# output arr2: [1, 20, 3, 40, 5, 60, 7, 80, 9]

2 Answers 2

1
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[a%2 == 0] *= 10
>>> a
array([ 0,  1, 20,  3, 40,  5, 60,  7, 80,  9])
Sign up to request clarification or add additional context in comments.

Comments

1

This is how you can do element-wise operation on array based on a condition:

arr[arr%2 == 0] *= 10

Note this does not create new array but modifies the array.

If you want a new array as well, you can copy the array after the operation:

arr2 = arr.copy()

Comments

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.