On May 20, 2005, at 8:49 AM, Alexandre wrote:
> On Fri, May 20, 2005 at 02:22:25PM +0200, Christian Meesters wrote:
>> 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
>> 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
Another alternative that takes two lines but perhaps is more readable
data[data<=0] = 1e-50 # if you don't mind modifying the original array
log_scaled = log(data)