1

I wanna index a 2d ndarray and fetch a subset of this ndarray. Then I assign this subset ndarray with another ndarry which has the same shape with this subset ndarray. But the original ndarray is not changed.

Here is an example.mat is not changed after the assignment operation.

What I want is assign a subset of ndarray with another ndarray.

import numpy as np
ma = np.array([1,2,3,4,5] * 5).reshape(5,5)
mask = np.array([False, True, False, True, True])
sub = np.array([[100,101, 102],
                [103, 104, 105],
                 [106,107,108]])
ma[mask][:,mask] = sub
print(ma)

what I expected is:

array([[1, 1, 3, 1, 5],
       [1, 100, 1, 101, 102],
       [1, 1, 3, 1, 5],
       [1, 103, 3, 104, 105],
       [1, 106, 3, 107, 108]])

But mat is not changed:

array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])
BAKE ZQ
  • 765
  • 6
  • 22
  • Not yet. I have change my question. – BAKE ZQ May 15 '19 at 06:18
  • Qestion updated – BAKE ZQ May 15 '19 at 11:47
  • This is not right. The output you want is `array([[1, 2, 3, 4, 5], |1, 100, 3, 101, 102], [1, 2, 3, 4, 5], [1, 103, 3, 104, 105], [1, 106, 3, 107, 108]])`. Besides, it's not very fair to completely change your questions and then downvote the answers because they don't apply anymore. I updated it – Ashargin May 15 '19 at 15:30
  • Thanks. That is the answer which could solve my problem. – BAKE ZQ May 16 '19 at 02:57

2 Answers2

0
np.where(mask, 1, np.where(mask, 1, ma).T).T
  1. np.where(mask, 1, ma) use mask to replace with 1 in columns
  2. np.where(mask, 1, np.where(mask, 1, ma).T) transpose the result and repeat again to mask rows
  3. np.where(mask, 1, np.where(mask, 1, ma).T).T Transpose back

Output

np.where(mask, 1, np.where(mask, 1, ma).T).T

array([[1, 1, 3, 1, 5],
       [1, 1, 1, 1, 1],
       [1, 1, 3, 1, 5],
       [1, 1, 1, 1, 1],
       [1, 1, 3, 1, 5]])
mujjiga
  • 16,186
  • 2
  • 33
  • 51
0

Do this :

ma[np.ix_(mask, mask)] = sub
Ashargin
  • 498
  • 4
  • 11