Copying values from one numpy matrix to another dependent on boolean mask

后端 未结 2 1024
迷失自我
迷失自我 2021-01-23 16:37

As a simple example, I\'ve got the following:

import numpy as np
a = np.matrix([[0.34, 0.44, 0.21, 0.51]])
a_max = np.matrix([[0.35, 0.40, 0.20, 0.50]])
<         


        
相关标签:
2条回答
  • 2021-01-23 17:23

    The minimum function seems to suffice:

    a = np.matrix([[999, 0.1, 0.1, 999]])
    a_max = np.matrix([[1, 2, 3, 4]])
    a_capped = np.minimum(a, a_max)
    
    print repr(a_capped)  # the printed result of matrix.__str__ is weird to me
    

    Prints:

    matrix([[1. , 0.1, 0.1, 4. ]])
    

    http://docs.scipy.org/doc/numpy/reference/generated/numpy.minimum.html

    0 讨论(0)
  • 2021-01-23 17:27

    Life's much easier if you work with arrays and not matrices; it Just Works (tm).

    >>> a = np.array([[0.34, 0.44, 0.21, 0.51]])
    >>> a_max = np.array([[0.35, 0.40, 0.20, 0.50]])
    >>> a[a > a_max] = a_max[a > a_max]
    >>> a
    array([[ 0.34,  0.4 ,  0.2 ,  0.5 ]])
    

    I guess you could use np.where, though:

    >>> a = np.matrix([[0.34, 0.44, 0.21, 0.51]])
    >>> a_max = np.matrix([[0.35, 0.40, 0.20, 0.50]])
    >>> np.where(a > a_max, a_max, a)
    matrix([[ 0.34,  0.4 ,  0.2 ,  0.5 ]])
    >>> 
    
    0 讨论(0)
提交回复
热议问题