Copying values from one numpy matrix to another de

2019-08-08 16:32发布

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]])

I would like to apply a transformation where anything in a, that is greater than a_max, is capped at a_max. I have tried to do this via:

a[a>a_max] = a_max[a>a_max]

however this throws an error:

ValueError: array is not broadcastable to correct shape

What is the proper way to do this? Ignore the fact that I am doing a simple maximum (I am guessing bumpy may have builtin tools to do that particular problem). My real problem uses a much more complicated set of booleans to create a boolean mask, which then should replace values from a replacement matrix.

2条回答
再贱就再见
2楼-- · 2019-08-08 16:46

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 ]])
>>> 
查看更多
【Aperson】
3楼-- · 2019-08-08 16:49

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

查看更多
登录 后发表回答