Setting values of Numpy array when indexing an indexed array -


i'm trying index matrix, y, , reindex result boolean statement , set corresponding elements in y 0. dummy code i'm using test indexing scheme shown below.

x=np.zeros([5,4])+0.1; y=x; print(x) m=np.array([0,2,3]); y[0:4,m][y[0:4,m]<0.5]=0; print(y) 

i'm not sure why not work. output want:

[[ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]] [[ 0.   0.1  0.   0. ]  [ 0.   0.1  0.   0. ]  [ 0.   0.1  0.   0. ]  [ 0.   0.1  0.   0. ]  [ 0.1  0.1  0.1  0.1]] 

but get:

[[ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]] [[ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]  [ 0.1  0.1  0.1  0.1]] 

i'm sure i'm missing under-the-hood details explains why not work. interestingly, if replace m :, assignment works. reason, selecting subset of columns not let me assign zeros.

if explain what's going on , me find alternative solution (hopefully 1 not involve generating temporary numpy array since actual y huge), appreciate it! thank you!

edit: y[0:4,:][y[0:4,:]<0.5]=0; y[0:4,0:3][y[0:4,0:3]<0.5]=0; etc.

all work expected. seems issue when index list of kind.

make array (this 1 of favorites because values differ):

in [845]: x=np.arange(12).reshape(3,4) in [846]: x out[846]:  array([[ 0,  1,  2,  3],        [ 4,  5,  6,  7],        [ 8,  9, 10, 11]]) in [847]: m=np.array([0,2,3]) in [848]: x[:,m] out[848]:  array([[ 0,  2,  3],        [ 4,  6,  7],        [ 8, 10, 11]]) in [849]: x[:,m][:2,:]=0 in [850]: x out[850]:  array([[ 0,  1,  2,  3],        [ 4,  5,  6,  7],        [ 8,  9, 10, 11]]) 

no change. if indexing in 1 step, changes.

in [851]: x[:2,m]=0 in [852]: x out[852]:  array([[ 0,  1,  0,  0],        [ 0,  5,  0,  0],        [ 8,  9, 10, 11]]) 

it works if reverse order:

in [853]: x[:2,:][:,m]=10 in [854]: x out[854]:  array([[10,  1, 10, 10],        [10,  5, 10, 10],        [ 8,  9, 10, 11]]) 

x[i,j] executed x.__getitem__((i,j)). x[i,j]=v x.__setitem__((i,j),v).

x[i,j][k,l]=v x.__getitem__((i,j)).__setitem__((k,l),v).

the set applies value produced get. if get returns view, change affects x. if produces copy, change not affect x.

with array m, y[0:4,m] produces copy (do need demonstrate that?). y[0:4,:] produces view.

so in short, if first indexing produces view second indexed assignment works. if produces copy, second has no effect.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -