What’s the most pythonic way to iterate 2 arrays correspondingly when using numpy?

Question:

Assume we need to compute the value of the function with numpy:

enter image description here

I know two methods:

METHOD I:

def func(b,X,Y):
  res = 0
  for i in range(len(X)):
    res += np.log(X[i] + b * Y[i])
  return res

METHOD II:

def func(b,X,Y):
  return np.sum(np.array([np.log(X[i) + b*Y[i]) for i in range(len(X))]))

Are both methods (1)pythonic (2) readable (3) efficient in running time? Is there any better implementation evaluated by these three metrics?

Asked By: outsider

||

Answers:

The second method works great
Because you have implemented the vectorized form such that the number of operations become very less compared to the method 1

Answered By: Varun Kumar

You don’t need to iterate through X and Y, numpy can broadcast the operations natively:

np.log(np.array(X) + b * np.array(Y)).sum()

If X and Y are already np.arrays:

np.log(X + b * Y).sum()
Answered By: Daniel F
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.