[Numpy-discussion] applying function under certain conditions

Alexandre Alexandre.Fayolle at logilab.fr
Fri May 20 05:53:04 EDT 2005


On Fri, May 20, 2005 at 02:22:25PM +0200, Christian Meesters wrote:
> Hi
> 
> I have a large 1D numarray array with some huge values and lots of 
> zeros. Now, for better representation I wanted to plot the logarithm. 
> Well, calculating the logarithm is not such a good idea if you have 
> zeros in your array ...
> However, how do you implement such cases like "only apply a function if 
> a certain condition is true", I'd like to ask whether there are nice 
> short snippets which could show such cases. My own code is 
> (unnecessarily?) long and ugly. I tried to combine 'where' and 
> 'greater', but didn't succeed. I guess I'm just don't see the wood for 
> the trees. How would you write this in my case?

Assuming your data contains only positive or null values,you could try
replacing zeros by a very small value before computing the log:

log_scaled = log(where(data, data, 1e-50)) 

This uses the fact that 0 is false and non-zero is true.

If you have negative values, you can use something like

log_scaled = log(where(data>0, data, 1e-50))

since data>0 will return a boolean array suitable for where. 

-- 
Alexandre Fayolle                              LOGILAB, Paris (France).
http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20050520/bd38c3fa/attachment.sig>


More information about the NumPy-Discussion mailing list