0

I have a numpy array of (m, 2) and I want to transform it to shape of (m, 1) using a function below.

def func(x):
    if x == [1., 1.]:
        return 0.
    if x == [-1., 1.] or x == [-1., -1.]:
        return 1.
    if x == [1., -1.]:
        return 2.

I want this for applied on each (2,) vector inside the (m, 2) array resulting an (m, 1) array. I tried to use numpy.vectorize but it seems that the function gets applied in each element of a array (which makes sense in general purpose case). So I have failed to apply it.

My intension is not to use for loop. Can anyone help me with this? Thanks.

1
  • 1
    Each condition has to be wrapped in (x == [1., 1.]).all(), then np.vectorize(func, signature='(n)->()')(arr) or np.apply_along_axis(func, 1, arr). Both are slower than the comprehension np.fromiter([func(x) for x in arr], dtype=float). Commented Jun 14, 2022 at 6:59

1 Answer 1

1
import numpy as np


def f(a, b):
    return a + b


F = np.vectorize(f)
x = np.asarray([[1, 2], [3, 4], [5, 6]]).T

print(F(*x))

Output:

[3, 7, 11]
Sign up to request clarification or add additional context in comments.

2 Comments

hi, your approach maybe right, but I don't think 1+2 = 5
Damn, you're right! Sorry, I've changed my answer.

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.