help regarding extracting a smaller list from larger one

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Sep 15 19:16:05 EDT 2011


>Nevertheless, I think list comprehension is what you want:
>     [ x  for x in A  if 3.0 <= x <= 8.0 ]
>will extract all the values between 3 and 8 from the array A and create 
>a new list containing them.

>If you want the new list to be a numpy array then
>     numpy.array([ x  for x in A  if 3.0 <= x <= 8.0 ])


I have been told that the following is much faster than list generation for filtering if you are using numpy arrays. I have not looked to see if this claim is accurate, but since it was one of the SciPy creators....I trust him :) YMMV

foo = numpy.array([
	[1.2,2.3,1.3],
	[4.3,2.1,6.2],
	[3.2,1.2,6.5],
	[1.4,2.1,4.3]])
#if we want 2nd element > 2 and 3rd element < 6
mask = (foo[:,2]>2)&(foo[:,2]<6)
v = foo[mask] #this is a view and if you want a new list, you will have to wrap it
# I assume np.array(v) will create new array (untested).

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list