Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

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

$
0
0

I have numpy.ndarrayA with shape S. I want to create numpy.ndarrayB 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?

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.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>