5

在 numpy 中:

Foo = 
array([[ 3.5,  0. ,  2.5,  2. ,  0. ,  1. ,  0. ],
       [ 0. ,  3. ,  2.5,  2. ,  0. ,  0. ,  0.5],
       [ 3.5,  0. ,  0. ,  0. ,  1.5,  0. ,  0.5]])

我想在 Foo 上执行一个函数,以便仅更改非零元素,即对于 f(x) = x(nonzero)+5:

array([[ 8.5,  0. ,  7.5,  7. ,  0. ,  6. ,  0. ],
       [ 0. ,  8. ,  8.5,  7. ,  0. ,  0. ,  5.5],
       [ 8.5,  0. ,  0. ,  0. ,  6.5,  0. ,  5.5]])

另外我希望数组的形状/结构保持不变,所以我不认为 Foo[np.nonzero(Foo)] 会起作用......

我如何在 numpy 中执行此操作?

谢谢!

4

2 回答 2

11
In [138]: foo = np.array([[ 3.5,  0. ,  2.5,  2. ,  0. ,  1. ,  0. ],
                          [ 0. ,  3. ,  2.5,  2. ,  0. ,  0. ,  0.5],
                          [ 3.5,  0. ,  0. ,  0. ,  1.5,  0. ,  0.5]])
In [141]: mask = foo != 0

In [142]: foo[mask] = foo[mask]+5

In [143]: foo
Out[143]: 
array([[ 8.5,  0. ,  7.5,  7. ,  0. ,  6. ,  0. ],
       [ 0. ,  8. ,  7.5,  7. ,  0. ,  0. ,  5.5],
       [ 8.5,  0. ,  0. ,  0. ,  6.5,  0. ,  5.5]])
于 2012-11-24T18:41:36.067 回答
2

您也可以按如下方式进行

>>> import numpy as np
>>> foo = np.array([[ 3.5,  0. ,  2.5,  2. ,  0. ,  1. ,  0. ],
...                           [ 0. ,  3. ,  2.5,  2. ,  0. ,  0. ,  0.5],
...                           [ 3.5,  0. ,  0. ,  0. ,  1.5,  0. ,  0.5]])
>>> foo[foo!=0] += 5
>>> foo
array([[ 8.5,  0. ,  7.5,  7. ,  0. ,  6. ,  0. ],
       [ 0. ,  8. ,  7.5,  7. ,  0. ,  0. ,  5.5],
       [ 8.5,  0. ,  0. ,  0. ,  6.5,  0. ,  5.5]])
>>>
于 2012-11-24T18:49:28.797 回答