[SciPy-user] Way to get values which are the same on two arrays
Michael Sorich
mike_sorich at hotmail.com
Sun Nov 3 20:49:08 EST 2002
Hi José,
I remember reading your question last week. Coincidently, I have just
written a function to find the intersection of 2 sets (using a histogram
function) for my own work. I'm not sure if it is the most efficient
method, but it seems to work.
from Numeric import *
def histogram(a, bins):
"""counts the number of values in a that fall into each of the bins
in bin"""
n = searchsorted(sort(a),bins)
n = concatenate([n,[len(a)]])
return asarray(n[1:]-n[:-1])
def intersection(a,b):
"""takes two 1D arrays and returns an array of values that are in
both arrays"""
if a.typecode() != 'l' or b.typecode() != 'l':
raise ValueError, "arrays must be of type Int"
#make bins from intersection of ranges
minab = max([minimum.reduce(a),minimum.reduce(b)])
maxab = min([maximum.reduce(a),maximum.reduce(b)])
# -> If either set is empty, or their ranges don't intersect
if maxab < minab or maxab < 0:
return None
bins = arange(minab,maxab+1)
return
minab+nonzero(logical_and(histogram(a,bins),histogram(b,bins)))
if __name__ == '__main__':
a = array([1,2,3,4,6])
b = array([4,5,6,1,7])
print intersection(a,b)
Hope this helps,
Michael Sorich
PhD Student
School of Pharmaceutical, Molecular and Biomedical Sciences
University of South Australia
Email: michael.sorich at postgrads.unisa.edu.au
mike_sorich at hotmail.com
--------------------------------
Hi,
I seem to remember a Numerical function that could produce the
list of
values (or array positions) which are common to two arrays. In other
words:
a1=[1,2,3,9,10]
a2=[1,4,9,10]
result is [1,9,10].
Browsing through the Numerical docs doesn't refresh my memory,
so any
kind souls?
many thanks,
José
--
José L Gómez Dans PhD student
Tel: +44 114 222 5582 Radar & Communications Group
FAX; +44 870 132 2990 Department of Electronic
Engineering
University of Sheffield UK
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.408 / Virus Database: 230 - Release Date: 24/10/2002
More information about the SciPy-User
mailing list