Srivatsan
Srivatsan

Reputation: 9363

Getting values OF a set in Python

I have 6 arrays, let's say a,b,c1,d1,c2,d2.

Arrays a and b have some common pairs of c1,c2 and d1,d2. I find these common pairs, i.e. those a and b which have the same c1,d1 and c2,d2 like this:

data_zcosmo_lastz = a
data_zphot_lastz = b
halo_id_zcosmo = c1 
halo_id_zphot = c2
idrep_zcosmo = d1
idrep_zphot = d2


file2freq1 = Counter(zip(c1,d1))
file2freq2 = Counter(zip(c2,d2))

set_a = set(file2freq1) & set(file2freq2) # common objects  

The above code gives set_a to have those common values of c1,d1 and c2,d2.

But how do I get the values of a and b of set_a?

i.e. I want the a and b values of set_a.

Example

a = [1,2,3,4,5]
b = [2,3,4,5,6]
c1 = [1,1,1,2,2]
d1 = [3,3,3,4,4]
c2 = [1,1,2,2,2]
d2 = [3,3,1,4,4]

so set_a = [(1,3),(1,3),(2,4),(2,4)]

Now I want those values of a and b that have these pairs. i.e.

a = [1,2,4,5] and b = [2,3,5,6]

Upvotes: 1

Views: 49

Answers (1)

tobias_k
tobias_k

Reputation: 82909

Still not 100% what you are asking. As I understand the question, you want the elements of a and b at those positions where the elements of c1 and d1 are the same as those of c2 and d2 respectively.

In this case, using set and Counter won't help, as those will erase any information on the position. Instead, just zip all those lists together...

for a_, b_, c1_, d1_, c2_, d2_ in zip(a,b,c1,d1,c2,d2):
    if (c1_,d1_) == (c2_,d2_):
        print(a_, b_)

... or just zip the c1,d1,c2,d2 lists and use enumerate to get the positions:

idx = [i for i, t in enumerate(zip(c1,d1,c2,d2)) if t[:2] == t[2:]]
print([(a[i], b[i]) for i in idx])

Alternatively, you could also use numpy for this, after converting your arrays to numpy.arrays doing e.g. A = np.array(a) and so on.

>>> match = np.logical_and(C1 == C2, D1 == D2)
>>> match
array([ True,  True, False,  True,  True], dtype=bool)
>>> A[match]
array([1, 2, 4, 5])
>>> B[match]
array([2, 3, 5, 6])

Upvotes: 1

Related Questions