Backgound
I want to generate random numbers with distributions(np.random.normal, np.random.poisson, etc.), passing seveal keyword parameters(loc, scale, size, etc. each one is a list) into it.
loc = [1,2,3,6,10]
scale = [4,6,7,8,5]
size = [10,9,7,8,5]
# When I know which kwargs is in use, this lambda function works
list(map(lambda x,y: np.random.normal(loc = x, size = y), loc,size))
# however, the number of kwargs may change and the kwargs themselves may change. It won't work with codes below. How to generlize the function above?
list(map(lambda **params: np.random.normal(**params),**{'loc':loc, 'scale': scale, 'size':size}))
list(map(lambda x,y: np.random.poisson(loc = x, size = y), loc,size))
Outputs:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-47-dfea011463fd> in <module>
----> 1 list(map(lambda **params: np.random.normal(**params),**{'loc':loc, 'size':size}))
TypeError: map() does not take keyword arguments
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-1f3449886ea1> in <module>
----> 1 list(map(lambda x,y: np.random.poisson(loc = x, size = y), loc,size))
<ipython-input-48-1f3449886ea1> in <lambda>(x, y)
----> 1 list(map(lambda x,y: np.random.poisson(loc = x, size = y), loc,size))
mtrand.pyx in numpy.random.mtrand.RandomState.poisson()
TypeError: poisson() got an unexpected keyword argument 'loc'
Question
Is there a way to use built-in/numpy to iterate over kwargs's elements?
CodePudding user response:
You can try this:
import numpy as np
params = dict(loc=[1,2,3,6,10],
scale=[4,6,7,8,5],
size=[10,9,7,8,5])
ds = (dict(zip(params.keys(), vals)) for vals in zip(*params.values()))
list(np.random.normal(**d) for d in ds)
CodePudding user response:
If you want to use map, you could do:
params = (loc, scale, size)
names = ('loc', 'scale', 'size')
list(map(lambda p: np.random.normal(**dict(zip(names, p))),
zip(*params)))
