简体   繁体   English

翻转二维 numpy 数组行中的两个值

[英]flip two values in rows of 2d numpy array

I wrote the following code to flip two values in rows of 2d numpy array.我编写了以下代码来翻转二维 numpy 数组行中的两个值。 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

You could use advanced indexing:您可以使用高级索引:

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

if points are same in each row, u can use code like如果每一行的点都相同,你可以使用类似的代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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