1

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!

1 Answer 1

1

You can directly return a numpy array from your function:

def foo(val):
    return np.column_stack((val*10, val*20 - 7))

Because val*10 invokes elementwise multiplication (special case of numpy broadcasting), the result will be another array of the same shape. The same applies to val*20 - 7. Then column_stack() just attaches the two arrays together to get the final output shape you want.

For the general case (N-D to (N+1)-D), you can use:

def foo(val):
    return np.stack((val*10, val*20 - 7), axis=-1)

which will stack your N-D arrays into a (N+1)-D array along the last dimension.

Sign up to request clarification or add additional context in comments.

2 Comments

Good point! I just tried and I found it works on 1-D array to 2-D array. However if the val is 2-D array the foo function won't return a 3-D array, still studying why...
@GarlicTseng I edited the answer for the general N-D case

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.