使用 numpy where to return 同一行不同列中的元素

Using numpy where to return an element in the same row but different column

我正在尝试使用 np.where 将同一行(但不同列)中的一个元素交换为另一个元素。

这是我目前的情况:

arr = np.random.random_integers(0,10,size=(10,10))
split = np.random.random_integers(0,10,size=arr[1,:].shape)
newloc = np.random.random_integers(0,10,size=arr[1,:].shape)
arr2 = np.where(arr>split,arr[0,newloc],arr)

我的问题是 arr[0,newloc] 中的 0 意味着它总是从 arr 的第 0 行开始。但如果有意义的话,我想要类似“same_row”的东西。

我想你要找的是arr[:, newloc]。这将允许您使用 newloc 的值索引 arr 的第二个轴(即列)。

np.where(arr > split, arr[:, newloc], arr)

这是一个包含两行的示例:

>> arr = np.random.randint(0, 10, size=(2,10))
>> split = np.random.randint(0, 10, size=arr.shape[1])
>> newloc = np.random.randint(0, 10, size=arr.shape[1])

>> arr
array([[2, 3, 0, 0, 1, 4, 6, 5, 1, 9],
       [9, 2, 6, 3, 2, 6, 3, 6, 2, 5]])

>> split
array([5, 7, 3, 5, 1, 6, 0, 8, 8, 6])

>> newloc
array([1, 7, 0, 5, 0, 7, 3, 6, 4, 8])

>> np.where(arr > split, 1, 0) # mask
array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
       [1, 0, 1, 0, 1, 0, 1, 0, 0, 0]])

>> np.where(arr > split, arr[:, newloc], -1)
array([[-1, -1, -1, -1, -1, -1,  0, -1, -1,  1],
       [ 2, -1,  9, -1,  9, -1,  3, -1, -1, -1]])

在那里,您可以检查是否正确替换了列。


我用过 np.random.randint in the above snippet since np.random.random_integers 已弃用。