简体   繁体   中英

How to replace specific indices of a matrix using numpy in python

Beginner level at python. I have a large matrix (MxN) that I want to process and a Mx1 matrix that contains some indices. What I would want is to replace each row of the MxN matrix with a NaN given that the column of that row is less than that of the listed with respect to the Mx1 indices matrix.

Say for example I have:

A = [1  2  3  4]
    [5  6  7  8]
    [9 10 11 12]

and

B = [0]
    [2]
    [1]

the resultant matrix should be

C = [1    2   3  4]
    [NaN NaN  7  8]
    [NaN 10  11 12]

I am trying to avoid using for loops because the matrix I'm dealing with is large and the this function will be repetitive. Is there an elegant pythonic way to implement this?

Check out this code:
here logic over which first method work is that create condition-matrix for np.where and which is done following ways

import numpy as np

A = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=np.float)
B = np.array([[0], [2], [1]])

B = np.array(list(map(lambda i: [False]*i[0]+[True]*(4-i[0]), B)))
A = np.where(B, A, np.nan)
print(A)

Method-2: using basic pythonic code

import numpy as np

A = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=np.float)
B = np.array([[0], [2], [1]])

for i,j in enumerate(A):
    j[:B[i][0]] = np.nan        

print(A)

Your arrays - note that A is float, so it can hold np.nan :

In [348]: A = np.arange(1,13).reshape(3,4).astype(float); B = np.array([[0],[2],[1]])
In [349]: A
Out[349]: 
array([[ 1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.],
       [ 9., 10., 11., 12.]])
In [350]: B
Out[350]: 
array([[0],
       [2],
       [1]])

A boolean mask were we want to change values:

In [351]: np.arange(4)<B
Out[351]: 
array([[False, False, False, False],
       [ True,  True, False, False],
       [ True, False, False, False]])

apply it:

In [352]: A[np.arange(4)<B] = np.nan
In [353]: A
Out[353]: 
array([[ 1.,  2.,  3.,  4.],
       [nan, nan,  7.,  8.],
       [nan, 10., 11., 12.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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