I have a function to convert a value to a list (or array). How can I use it to convert a N-D array to another (N+1)-D array? The code below needs to generate a list then convert to <numpy.ndarray>. I'm wonder if there is a more efficient way (maybe some constructor for <numpy.ndarray>?).
# # assume we have a function foo
# def foo(val):
# return [val*10, val*20 - 7]
# # how can we use this function to convert a N-D array to another (N+1)-D array?
# # here is my tried
import numpy as np
def foo(val):
return [val*10, val*20 - 7]
a = np.arange(3) # 'numpy.ndarray', [0 1 2]
b = [foo(val) for val in a]
print (type(b)) # not good, it is a 'list'
print (b) # [[0, -7], [10, 13], [20, 33]]
b = np.array(b).reshape((3, 2))
print (type(b)) # this is what I want 'numpy.ndarray'
print (b) # will be what I want:
# [[ 0 -7]
# [10 13]
# [20 33]]
If there is no <numpy.ndarray> constructor for this. Should I generate a new ndarray (maybe with "numpy.zeros") and fill the value? Or it is recommend to generate a list then convert it to a ndarray? Not sure which one is faster.
Thanks!