简体   繁体   中英

“flip” values in numpy array?

I have a list of numbers within a range of 1.. n I want to 'flip' some of the numbers, but it shouldnt repeat any of the existing numbers.

I imagine it this way:

  1. pick numbers to flip
  2. flip them but check that they dont repeat

Here is step 1:

  lst = np.array([5,9,88,55,90,43])
 In [95]: z = np.random.choice(lst, 2,replace=False)
 Out[95]: array([ 9, 43])

    ixs = np.where(lst == z)[0]
    #does not guarantee that the new numbers are not already in lst!
    lst[ixs] = np.random.choice(xrange(0,n),2,replace=False)

now how do i make sure that the new random numbers dont repeat without doing checks in a loop.

Any other numpy way?


Flip mean change from one value to another. You can think of the list of numbers as indexes to a bitarray, where the number specifies if the bit is 1.

So flipping means for every flip of 1 => 0, flip another bit from 0 => 1

in: np.array([5,9,88,55,90,43]) out: np.array([5,9,46,55,21,43])

two number was changed

You can use sets.

s = set(xrange(0, n))

lst[ixs] = np.random.choice(s.difference(lst), 2, replace=False)

It's arguable if it's much more efficient, but it is certainly cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM