During each iteration step in a for-loop I compute an array that looks like
test = array([-0.23401695, -0.3880519 , -0.38805333, -0.38755048, -0.20781614,
-0.70836718, -0.38785778, -0.2346411 , -0.38757777, -0.38597846,
0.74324752, -0.38802888, -0.38768468, 0.25609106, -0.38759492,
-0.38601501, 0.12539226, -0.38780387, 0.53026535, -0.38773322,
-0.16896715, -0.54030724, -0.2340172 , 0.74325264, 0.47274894,
-0.38797809, -0.38803523, -0.2237936 , 0.85406766, -0.23401624,
-0.38803279, -0.38800347, -0.38793145, -0.38761207, -0.38795527,
-0.62081793, -0.38803845, -0.21677125, -0.38799521, 0.868606 ,
-0.3880574 , -0.38598402, 0.74379804, -0.38792198, -0.2026838 ,
-0.38805706, -0.38600679, -0.02927724, 0.46588779, -0.20076108])
I want to determine the number of elements in the array test that are similar, eg the number of elements that looks similar as -0.38.....
I tried something
for i in test:
counter = 0
for j in test:
if abs(i - j) < 10**(-2):
counter += 1
if counter > 20:
elements = counter - 1 # -1 for the case i=j
break
elements # --> 25
that works under the assumption, that i can estimate the number of similar elements (if counter > 20).
Does someone know how to generalize this (without the trick _ if counter > 20 _ which will not work for all cases).
If I understand the question correctly, you can get the number of similar elements using collections.Counter
coupled with np.ndarray.round()
:
>>> test = np.array(...)
>>> Counter(test.round(2))
Counter({-0.23: 4,
-0.39: 26,
-0.21: 1,
-0.71: 1,
0.74: 3,
0.26: 1,
0.13: 1,
0.53: 1,
-0.17: 1,
-0.54: 1,
0.47: 2,
-0.22: 2,
0.85: 1,
-0.62: 1,
0.87: 1,
-0.2: 2,
-0.03: 1})
>>> len(Counter(test.round(2))) # Number of different elements
17
>>> Counter(test.round(2)).most_common()[0] # Get the most frequent item (thx @Mike Müller)
(-0.39, 26)
Dont check for counter > 20
, just return the elements based on counter.
for i in test:
counter = 0
for j in test:
if abs(i - j) < 10**(-2):
counter += 1
elements = counter - 1
break
OR
start with counter = -1 and just return counter/or elemetns
for i in test:
counter = -1
for j in test:
if abs(i - j) < 10**(-2):
counter += 1
elements = counter
break
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.