numpy仅在保留数组结构的同时对非零部件执行功能

时间:2012-11-24 18:36:29

标签: python numpy

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(非零)+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中执行此操作?

谢谢!

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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]])
>>>