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!

1
  • 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? Commented Oct 24, 2019 at 8:20

1 Answer 1

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.        ])]
Sign up to request clarification or add additional context in comments.

2 Comments

is that any faster?
@Joe True, there are a lot of cases where looping is faster. Plus, essentially a for loop as seen in notes.

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.