简体   繁体   English

numpy 向量化在 (2,) 数组上的使用

[英]numpy vectorize use on (2,) array

I have a numpy array of (m, 2) and I want to transform it to shape of (m, 1) using a function below.我有一个(m, 2)的 numpy 数组,我想使用下面的函数将其转换为(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.

I want this for applied on each (2,) vector inside the (m, 2) array resulting an (m, 1) array.我希望将此应用于(m, 2)数组中的每个(2,)向量,从而产生一个(m, 1)数组。 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).我尝试使用numpy.vectorize但似乎该函数被应用于数组的每个元素(这在通用情况下是有意义的)。 So I have failed to apply it.所以我没有应用它。

My intension is not to use for loop.我的意图是不使用 for 循环。 Can anyone help me with this?谁能帮我这个? Thanks.谢谢。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM