Reputation: 11
I would like to 'flip' the values in a matrix, similar to numpy.absolute()
, but flipping around the average value in the matrix; sort of like a fold.
The code below works, but I'd ideally like something that's more pythonic / faster. For my purposes, my array is 360x360, and this 'flipping' needs to be done many, many times, so running a 'for' loop through each and every element in the array seems like a bad idea.
import numpy as np
arr = np.array([0,1,2,3,4])
avg = np.average(arr)
for i in range(len(arr)):
x = arr[i]
if x < avg:
arr[i] = x + avg
print(arr)
>>> [2,3,2,3,4]
Thanks!
Upvotes: 1
Views: 71
Reputation: 64318
This is the numpy way:
arr[arr < avg] += avg
The expression arr < avg
creates a mask for selecting the elements in arr
which are less than avg
.
arr[...]
selects those elements in arr
.
+= avg
increments them.
Upvotes: 2