Reputation: 11657
Suppose you have an array of two arrays. How can you make a function correctly separate the parts and apply the lambda
function here on each of them?
import numpy as np
a=np.asarray([[1]])
b=np.asarray([[1,2]])
r=np.asarray([a,b])
f=lambda x,y:x[:,0]+y
print f(*r)
This code will rise: IndexError: too many indices
. However simple change of a
two a (1,2)
array will change everything since numpy makes r
an ndarray
and correctly apply function to each of a
and b
. I understand this is because that what f
gets for its first argument is [array([[1]])]
but not [[1]]
. Is there any way to generate the same behaviour in the first case as well?
import numpy as np
a=np.asarray([[1,2]])
b=np.asarray([[1,3]])
r=np.asarray([a,b])
f=lambda x,y:x[:,0]+y
print f(*r)
With output:
[[2 4]]
EDIT: Just to clarify since f
will be called in my real code for million times and its more complex its important for me to keep this procedure as efficient as possible. Thanks.
Upvotes: 0
Views: 60
Reputation: 97331
You need to make a asobjectarray()
function:
import numpy as np
def asobjectarray(alist):
r = np.ndarray(len(alist), object)
r[:] = alist
return r
a = np.asarray([[1]])
b = np.asarray([[1,2]])
r = asobjectarray([a,b])
f=lambda x,y:x[:,0]+y
print f(*r)
Upvotes: 1