Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create numpy.ndarray A from existing B using various functions depending on corresponding value in B?

I have numpy.ndarray A with shape S. I want to create numpy.ndarray B with same shape but different value type. Also, I want to use various functions to transform element of A into corresponding element of B, but it’s guaranteed that return type of all these functions will be the same.

Long story short, I would like to do something like this:

def func1():
    return np.zeros(5)

def func2():
    return np.ones(5)

def func(val):
    return func2() if val & 1 else func1()

A = np.random.randint(0, 100, (10, 10))
B = np.array((10, 10, 5))
for i in range(10):
    for j in range(10):
        B[i, j] = func(A[i, j])

What is the most efficient/elegant way to do such an operation using numpy?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to use functions from paragraph "Functional programming" from numpy’s API Reference, but they either do not work piecewise or do not support change of value type.

P.S. Problem solved thanks to @bill. We can apply func to whole row at once using np.apply_along_axis.

>Solution :

Your code doesn’t execute (IndexError) so it’s hard to know what you want to do exactly.

Is this what you wanted?

B = np.where(A & 1, 1, 0)
array([[1, 1, 0, 1, 1, 0, 0, 0, 0, 1],
       [0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
       [1, 1, 1, 0, 0, 1, 0, 1, 1, 0],
       [1, 1, 0, 1, 0, 1, 1, 0, 1, 0],
       [0, 0, 0, 0, 1, 1, 0, 1, 0, 1],
       [1, 0, 0, 0, 1, 1, 0, 1, 1, 0],
       [0, 0, 1, 1, 0, 0, 0, 0, 0, 1],
       [1, 1, 0, 0, 1, 1, 0, 1, 0, 0],
       [0, 1, 1, 1, 1, 0, 1, 0, 1, 1],
       [0, 1, 0, 0, 0, 0, 1, 0, 1, 1]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading