I have a numpy array and I want to invert it in a sense that I want to swap max and min, second max and second min and so on.
arr = [1, 2, 1, 3, 2, 4, 1, 4]
# Output should be [4, 3, 4, 2, 3, 1, 4, 1]
arr = [4, 4, 1, 2]
# Output should be [1, 1, 4, 2]
Is there a way to vectorize this?
CodePudding user response:
Assuming you want to swap the unique values, you can use np.unique
to get both the sorted unique values and the index of the selected unique value in the sorted unique value. Then, you can revert the array of unique values to swap the min and max values. After that, the index will reference swapped min-max values, so you can just extract them using and indirect indexing. Here is the resulting fully vectorized code:
arr = np.array([1, 2, 1, 3, 2, 4, 1, 4])
uniqueItems, ids = np.unique(arr, return_inverse=True)
out = uniqueItems[::-1][ids]
# out: [4, 3, 4, 2, 3, 1, 4, 1]
CodePudding user response:
I think it can at least be partially vectorized:
import numpy as np
data = np.array([1, 2, 1, 3, 2, 4, 1, 4])
uniques = np.unique(data)
mapping = np.dstack((uniques, np.flip(uniques)))[0]
result = np.copy(data)
for key, value in mapping:
result[data == key] = value
print(result)
Output is as expected:
[4 3 4 2 3 1 4 1]