【问题标题】:Python- Numpy array in function with conditionsPython-具有条件的函数中的Numpy数组
【发布时间】:2018-08-05 12:38:32
【问题描述】:

我有一个 numpy 数组(比如 xs),我正在为此编写一个函数来创建另一个数组(比如 ys),该数组的值与 xs 的值相同,直到 xs 的前半部分和 xs 的两倍剩下的一半。例如,如果 xs=[0,1,2,3,4,5],则所需输出为 [0,1,2,6,8,10]

我写了以下函数:

import numpy as np
xs=np.arange(0,6,1)

def step(xs):
    ys1=np.array([]);ys2=np.array([])
    if xs.all() <=2:
        ys1=xs
    else:
        ys2=xs*2
    return np.concatenate((ys1,ys2))

print(xs,step(xs))

产生输出:`array([0., 1., 2., 3., 4., 5.]),即不执行第二个条件。有人知道如何解决吗?提前致谢。

【问题讨论】:

  • if xs.all() &lt;=2:True 所以ys1 被分配了xs 并且ys2 仍然是一个空数组。在串联时,您只需返回 ys1xs 相同

标签: python arrays function numpy


【解决方案1】:

您可以使用向量化操作而不是 Python 级迭代。使用下面的方法,我们首先复制数组,然后将数组的后半部分乘以 2。

import numpy as np

xs = np.arange(0,6,1)

def step(xs):
    arr = xs.copy()
    arr[int(len(arr)/2):] *= 2
    return arr

print(xs, step(xs))

[0 1 2 3 4 5] [ 0  1  2  6  8 10]

【讨论】:

    【解决方案2】:
    import numpy as np
    
    xs=np.arange(0,6,1)
    
    def f(a):
        it = np.nditer([a, None])
        for x, y in it:
            y[...] = x if x <= 2 else x * 2
        return it.operands[1]
    
    print(f(xs))
    

    [ 0  1  2  6  8 10]
    

    对不起,我没有找到你的错误,但我觉得它可以以不同的方式实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-17
      • 2016-08-31
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2019-10-25
      • 1970-01-01
      相关资源
      最近更新 更多