numpy-使用给定数组值的切片更新值 [英] numpy - update values using slicing given an array value

查看:95
本文介绍了numpy-使用给定数组值的切片更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数组

import numpy as np
a = np.arange(0,36).reshape((6,6)).T

[[ 0  6 12 18 24 30]
 [ 1  7 13 19 25 31]
 [ 2  8 14 20 26 32]
 [ 3  9 15 21 27 33]
 [ 4 10 16 22 28 34]
 [ 5 11 17 23 29 35]]


for i in a[:,0]:
    a[i][i:] = 0

[[ 0  0  0  0  0  0]
 [ 1  0  0  0  0  0]
 [ 2  8  0  0  0  0]
 [ 3  9 15  0  0  0]
 [ 4 10 16 22  0  0]
 [ 5 11 17 23 29  0]]

我想知道是否可以使用"第一列"来更新(清除)值,以此作为切片在轴= 1上的开始的指示器,并且在不进行此操作的情况下进行使用循环.

I wish to know if I can update (wipe out) the values using the "first column" as an indicator of the start of the slice on axis =1 and do this without using a loop.

请注意,"第一列"中的值不一定与示例中所示的顺序相同,因此numpy.tril在这里不适合我.我确实知道"第一列"中的值永远不会大于axis = 1的大小.

Please note the values in "first column" will not necessarily be in order as shown in the example so numpy.tril is not appropriate for me here. I do know that the value in "first column" will never be bigger than the size of axis=1.

推荐答案

这样的事情怎么样?请注意,我已经对第一列进行了改组.

How about something like this? Note that I've shuffled the first column.

>>> a = np.arange(0,36).reshape((6,6)).T; a[2,0] = 4; a[4,0] = 2;
>>> a
array([[ 0,  6, 12, 18, 24, 30],
       [ 1,  7, 13, 19, 25, 31],
       [ 4,  8, 14, 20, 26, 32],
       [ 3,  9, 15, 21, 27, 33],
       [ 2, 10, 16, 22, 28, 34],
       [ 5, 11, 17, 23, 29, 35]])
>>> a[np.arange(a.shape[1])[None,:] >= a[:,0,None]] = 0
>>> a
array([[ 0,  0,  0,  0,  0,  0],
       [ 1,  0,  0,  0,  0,  0],
       [ 4,  8, 14, 20,  0,  0],
       [ 3,  9, 15,  0,  0,  0],
       [ 2, 10,  0,  0,  0,  0],
       [ 5, 11, 17, 23, 29,  0]])

这篇关于numpy-使用给定数组值的切片更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆