Extend Numpy Array In A Way Compatible With Builtin Arrays
I am trying to write code that would not depend on whether the user uses np.array or a builtin array. I am trying to avoid checking object types, etc. The only problem that I have
Solution 1:
NumPy's append() works on lists too!
>>> np.append([1,2,3], [1,2,3])
array([1, 2, 3, 1, 2, 3])
If you want to automatically make the result be the same type as the input, try this:
mytype = type(a)
arr = np.append(a, b)
result = mytype(arr)
Solution 2:
Even if your function is flexible on input, your output should be of specific type. So I would just convert to desired output type.
For example, if my functions is working with numpy.array
and returns a numpy.array
, but I want to allow list
s to be input as well, the first thing I would do is convert list
s to numpy.array
s.
Like this:
def my_func(a, b):
a = np.asarray(a)
b = np.asarray(b)
# do my stuff here
Post a Comment for "Extend Numpy Array In A Way Compatible With Builtin Arrays"