3

I have this code snippet:

import numpy as np

a=np.array([5,6,7,8,9])
b=np.array([5,6,7,8,9])

scoreA = np.array([float(1) / (i + 1) for i in range(len(a))])
scoreB = np.array([0 for i in range(len(b))])

for eleA in a:
    if eleA in b:
        i, = np.where(b == eleA)
        i = i[0]
        j, = np.where(a == eleA)
        j = j[0]
        scoreB[i] = scoreA[j]

        print "B is: %f" % scoreB[i]
        print "A is: %f" % scoreA[j]

So the basic idea is: for arrays a and b, if an element is found in both of them, then I'll assign the score of that element in scoreA to scoreB. But the result is like this:

B is: 1.000000
A is: 1.000000
B is: 0.000000
A is: 0.500000
B is: 0.000000
A is: 0.333333
B is: 0.000000
A is: 0.250000
B is: 0.000000
A is: 0.200000

which means the line:

scoreB[i] = scoreA[j]

is not working properly? How can I resolve this?

1
  • 2
    IIUC, just do : mask = a==b; scoreB[mask] = scoreA[mask]. Commented Aug 24, 2017 at 10:24

1 Answer 1

2

Your solution is rather strange and it is better to make it as @Divakar mentioned. But anyway the straitforward problem is that scoreA and scoreB have different types: float64 and int64.

make

scoreA = np.array([float(1) / (i + 1) for i in range(len(a))],dtype=float)
scoreB = np.array([0 for i in range(len(b))],dtype=float)

or some other dtype to make sure that all your scores have the same type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.