If I have a numpy array such as:
[0,1,0,2,2]
and I'd like to simultaneously flip the 0s and 2s in the list (to get [2,1,2,0,0]), what would be the best way?
I wrote a simple function to do this. You pass it the two numbers and the matrix you want the numbers flipped in, and it returns the new matrix.
def flip(a,b,mat):
NewMat=np.array(size(mat))
for entry in range(len(mat)):
if mat[entry]==a:
NewMat[entry]=b
else if mat[entry]==b:
NewMat[entry]=a
else:
NewMat[entry]=mat[entry]
return NewMat
for loopYou could do some additions with the input array to have the desired effect, as listed in the code below -
def flip_vals(A,val1,val2):
# Find the difference between two values
diff = val2 - val1
# Scale masked portion of A based upon the difference value in positive
# and negative directions and add up with A to have the desired output
return A + diff*(A==val1) - diff*(A==val2)
Sample run -
In [49]: A = np.random.randint(0,8,(4,5))
In [50]: A
Out[50]:
array([[0, 2, 3, 0, 3],
[1, 5, 6, 6, 3],
[1, 6, 7, 6, 4],
[3, 7, 0, 3, 7]])
In [51]: flip_vals(A,3,6)
Out[51]:
array([[0, 2, 6, 0, 6],
[1, 5, 3, 3, 6],
[1, 3, 7, 3, 4],
[6, 7, 0, 6, 7]])
If by best, you meant performance wise, I would go with the other logical indexing based solution.
2 - x, wherexis your array. There may be other shortcuts available depending on what exactly you mean by "more varied arrays".