0

I want to ask something that is related with this question posted time ago Operation on numpy arrays contain rows with different size . The point is that I need to do some operations with numpy arrays that contain rows with different size.

The standard way like "list2*list3*np.exp(list1)" doens't work since the rows are from different size, and the option that works is using zip. See the code below.

import numpy as np
import time

list1 = np.array([[2.,0.,3.5,3],[3.,4.2,5.,7.1,5.]])
list2 = np.array([[2,3,3,0],[3,8,5.1,7.6,1.2]])
list3 = np.array([[1,3,8,3],[3,4,9,0,0]])

start_time = time.time()

c =[]
for i in range(len(list1)):
    c.append([list2*list3*np.exp(list1) for list1, list2,list3 in zip(list1[i], list2[i],list3[i])])

print("--- %s seconds ---"% (time.time()-start_time))

I want to ask if exist a much more efficient way to perform this operations avoiding a loop an doing in a more numpy way. Thanks!

Joe
  • 189
  • 10
  • What is the purpose of having them in that specific shape? Would it be a problem to adapt the shape within the function so the multiplication can be done in one go? – Marc Oct 24 '19 at 08:20

1 Answers1

1

This should do it:

f = np.vectorize(lambda x, y, z: y * z * np.exp(x))

result = [f(*i) for i in np.column_stack((list1, list2, list3))]

result

#[array([ 14.7781122 ,   9.        , 794.77084701,   0.        ]),
# array([ 180.76983231, 2133.96259331, 6812.16400281,    0.        ,    0.        ])]
zipa
  • 27,316
  • 6
  • 40
  • 58
  • is that any faster? – hpaulj Oct 24 '19 at 10:13
  • @Joe True, there are a lot of cases where looping is faster. Plus, [essentially a for loop](https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html) as seen in notes. – zipa Oct 24 '19 at 10:44