1

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?

3
  • Are the only values in the array 0, 1 or 2? Commented Aug 1, 2015 at 0:36
  • yup, but i'd like a solution that's adaptable to more varied arrays as well if poss.. Commented Aug 1, 2015 at 0:38
  • For your example array you could simply compute 2 - x, where x is your array. There may be other shortcuts available depending on what exactly you mean by "more varied arrays". Commented Aug 1, 2015 at 1:00

3 Answers 3

7

This is a straightforward application of conditionals in numpy.

def switchvals(arr, val1, val2):
    mask1 = arr == val1
    mask2 = arr == val2
    arr[mask1] = val2
    arr[mask2] = val1
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Since we're dealing with numpy arrays, boolean indexing will probably be much faster than a for loop
0

You 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.

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.