MathPro
MathPro

Reputation: 19

flip two values in rows of 2d numpy array

I wrote the following code to flip two values in rows of 2d numpy array. However, I am wondering if there is a better way to do this. thanks in advance

def mtn(offg):
    for row in range(offg.shape[0]):
        point1 = random.randint(0, 139)
        point2 = random.randint(0, 139)
        temp = offg[row, point1]
        offg[row, point1] = offg[row, point2]
        offg[row, point2] = temp
    return offg

Upvotes: 0

Views: 83

Answers (2)

tstanisl
tstanisl

Reputation: 14127

You could use advanced indexing:

offg[:,[p1, p2]] = offg[:,[p2, p1]]

Upvotes: 1

Demetry Pascal
Demetry Pascal

Reputation: 544

if points are same in each row, u can use code like

tmp = offg[:,p1].copy()
offg[:,p1] = offg[:,p2]
offg[:,p2] = tmp

Upvotes: 0

Related Questions