Reputation: 29
I have two arrays (A & B). I would like to calculate the % of users of array A , who are included in array B. I have tried but I can´t find the solution.
Upvotes: 2
Views: 128
Reputation: 180411
You only need to create one set and sum the times an element in a is in the set of the members in b:
st = set(b)
perc = sum((ele in st for ele in a),0.0) / len(a) * 100
If you actually have numpy arrays:
import numpy as np
a, b = [1, 3], [1, 4,3]
perc = np.in1d(a, b).sum() / 100.0 / len(a)
Upvotes: 0
Reputation: 297
The most pyhtonic way is like Rogalski above commented.
Python in my opinion is very strong at sets: https://docs.python.org/2/library/sets.html
you can make an intersection in two ways
set(A) & set(B) or set(A).intersection(set(B))
And the formula is like mentioned above (just corrected)
100 * len(set(A) & set(B)) / len(set(A))
Upvotes: 4
Reputation: 36033
100.0 * sum((x in B) for x in A) / len(A)
If B
is large, use a set for efficiency:
100.0 * len(set(B).intersection(A)) / len(A)
Upvotes: 9