numpy vectorize在(2,)数组上使用

发布于 2025-02-07 04:55:38 字数 443 浏览 1 评论 0原文

我有一个(m,2)的数组数组,我想使用以下功能将其转换为(m,1)的形状。

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.

我希望将其应用于(M,2)内的每个(2,)向量,数组导致(M,1) array。我尝试使用numpy.Dectorize,但是似乎该函数在数组的每个元素中都应用(在通常的情况下是有意义的)。所以我没有应用它。

我的目的不是用于循环。谁能帮我吗?谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

相权↑美人 2025-02-14 04:55:38
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))

输出:

[3, 7, 11]
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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文