[SciPy-User] embarassingly basic question
Zachary Pincus
zachary.pincus at yale.edu
Sun Sep 27 14:27:27 EDT 2009
Hmm, so the original question was, "if the value in the array is lower
than x, then make it zero, if the value is greater than x, then make
it 1", which requires that if the value of the array equals x, it
should be unchanged... Gökhan's answer does correctly and mine below
does not.
However, this is a bit of an unusual request, more often one would
want to make everything zero if it's < x and 1 if >= x (or <= and >,
respectively). In this case, the answers below work, but there's an
even simpler special-case answer for zeros and ones:
a >= x
gives a boolean array with zeros where a < x and ones where a >= x.
(All basic logic operations work here.)
Zach
On Sep 27, 2009, at 2:18 PM, Zachary Pincus wrote:
> numpy.where is also useful for this case:
>
> In : numpy.where(numpy.arange(10) < 5, 0, 1)
> Out: array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
>
> Note that there's a lot going on in this example, including
> broadcasting the scalar 0 and 1 values to 1D arrays... where can take
> any array with a "compatible" shape as the second or third argument:
> In : numpy.where(numpy.arange(10) < 5, numpy.arange(20, 30),
> numpy.arange(60, 70))
> Out: array([20, 21, 22, 23, 24, 65, 66, 67, 68, 69])
>
>
> On Sep 27, 2009, at 1:53 PM, Gökhan Sever wrote:
>
>> On Sun, Sep 27, 2009 at 12:44 PM, Gustaf Nilsson <gustaf at laserpanda.com
>>> wrote:
>> Hi
>> (this might even be a numpy question, not scipy)
>> how do i do conditionals numpy arrays?
>> What i want to do is: if any value in the array is lower than x,
>> then make it zero, if the value is greater than x, then make it 1
>>
>> i tried googling the answer, but dont think i used the right keywords
>>
>> cheers
>> Gusty
>>
>>
>>
>> Robert Kern must be sleeping :)
>>
>> I[1]: a = arange(10)
>>
>> I[2]: a[a<5] = 0
>>
>> I[3]: a
>> O[3]: array([0, 0, 0, 0, 0, 5, 6, 7, 8, 9])
>>
>> I[4]: a[a>5] = 1
>>
>> I[5]: a
>> O[5]: array([0, 0, 0, 0, 0, 5, 1, 1, 1, 1])
>>
>>
>> --
>> ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
>>
>> _______________________________________________
>> SciPy-User mailing list
>> SciPy-User at scipy.org
>> http://mail.scipy.org/mailman/listinfo/scipy-user
>>
>>
>>
>>
>> --
>> Gökhan
>> _______________________________________________
>> SciPy-User mailing list
>> SciPy-User at scipy.org
>> http://mail.scipy.org/mailman/listinfo/scipy-user
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
More information about the SciPy-User
mailing list