0

Someone suggested that in python it is possible to get a boolean array with criteria applied to certain numerical array.

Say I have array1 = [1, 2, 3, 4, 5] I want to apply the criteria x>2 & x<5 so that the resulting array would be something like >>> [F, F, T, T, F]

I wonder if this is possible and how should I get there, thanks!
(please just ignore any syntax mistake above as I'm new to python, sorry for any potential confusion those might cause)

LilMuji
  • 57
  • 1
  • 1
  • 11

1 Answers1

2

array1 = [1, 2, 3, 4, 5] is called a list in python. array usually means numpy.array here.

In numpy:

import numpy as np
arr=np.array([1, 2, 3, 4, 5])
(arr>2)&(arr<5)

Or without numpy:

In [5]:

array1 = [1, 2, 3, 4, 5]
[2<item<5 for item in array1]
Out[5]:
[False, False, True, True, False]
In [11]:

array1 = [1, 2, 3, 4, 5]
['T' if 2<item<5 else 'F' for item in array1]
Out[11]:
['F', 'F', 'T', 'T', 'F']

Using lambda with map is usually the recipe for slow code:

In [6]:

%timeit list(map(lambda x: x > 2 and x < 5, [1, 2, 3, 4, 5]))
100000 loops, best of 3: 7.63 µs per loop
In [7]:

%timeit [2<item<5 for item in [1, 2, 3, 4, 5]]
100000 loops, best of 3: 4 µs per loop
CT Zhu
  • 52,648
  • 17
  • 120
  • 133
  • Could you plz tell me for my purpose is there any difference between using an array and a list? It seemed to me like only an array could do the work here, I don't know if it is correct. – LilMuji Jul 01 '14 at 05:30
  • @LilMuji: There's plenty: http://stackoverflow.com/questions/993984/why-numpy-instead-of-python-lists – user2357112 Jul 01 '14 at 05:32
  • 3
    You could always just do `[2 – Sukrit Kalra Jul 01 '14 at 05:33
  • @LilMuji, `array` usually mean other things in `python`, say, `array` module: https://docs.python.org/2/library/array.html or `numpy.array`, not thing magic, just a terminology. – CT Zhu Jul 01 '14 at 05:33
  • @SukritKalra, maybe OP wants `'T'` and `'F'`s. Who knows. – CT Zhu Jul 01 '14 at 05:41
  • @CTZhu what do you mean by slow code? it runs slow with a large amount of data? :( My goal is actually to apply this boolean list to something else in order to select elements at certain position. Say with `[False, False, True, True, False]` I want to turn `[0, 2, 4, 6, 8]` into `[4, 6]` or `[0, 0, 4, 6, 0]`, that's why I was trying to get the boolean list first... Anyway thanks a lot – LilMuji Jul 01 '14 at 05:51
  • Slow code was referring to that `lambda` `map` solution, never mind on that. To get `[4,6]`, do: `[item for item in array1 if 2 – CT Zhu Jul 01 '14 at 05:54
  • @CTZhu I'm actually applying that position info (which I get from list1) onto a different list(list2) through the boolean list.. so I guess `[item for item in array1 if 2 – LilMuji Jul 01 '14 at 06:01
  • `[item2 for item1,item2 in zip(array1, array2) if 2 – CT Zhu Jul 01 '14 at 06:06
  • @CTZhu it worked!! <3 this is way too cool – LilMuji Jul 01 '14 at 06:12