【问题标题】:Is there universal if function in numpy?numpy中是否有通用的if函数?
【发布时间】:2013-05-12 11:07:34
【问题描述】:

我有三个系列。我需要按元素执行以下操作:

  1. 比较第一个和第二个系列的值。
  2. 如果第一个较大,则取第三个系列中元素的圆弧。
  3. 否则取反余弦。

这是我到目前为止所做的:

numpy.if(numpy.less(s1,s2),numpy.arcsin(s3),numpy.arccos(s3))

不幸的是 if 不起作用,因为numpy.if 不存在。有没有办法克服这个问题?

【问题讨论】:

    标签: python numpy scipy pandas series


    【解决方案1】:

    我想你在找numpy.where:

    np.where(s1<s2, np.arcsin(s3), np.arccos(s3))
    

    对于一维输入,

    where(condition, [x, y])
    

    等价于

    [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
    

    【讨论】:

    • 谢谢!顺便说一句,我不知道&lt; 是这样工作的。我想我需要使用numpy.less 函数。如果&lt; 与系列一起使用,为什么我们需要numpy.less
    • @Roman 一个用例是如果您必须将函数作为其他函数的参数传递。你不能做call_a_function(&lt;, a, b),你必须做call_a_function(numpy.less, a, b)。这就是 python 中存在operator 模块的原因。
    【解决方案2】:

    unutbu 做得很好。我建议一个没有where 的等价物(但无论如何都有numpy

    import numpy as np
    
    s1=[2,1,2,5,4,6]
    s2=[1,2,4,5,7,8]
    s3=[0.1,0.4,0.5,0.6,0.1,0.1]
    
    res = [xv if c else yv for (c,xv,yv) in zip([si1<si2 
              for si1,si2 in zip(s1,s2)], list(np.arcsin(s3)), list(np.arccos(s3)))]
    

    如果你打印zip(),你会得到这个列表

    >>> 
    [(False, 0.1001674211615598, 1.4706289056333368), (True, 0.41151684606748806, 1.1592794807274085), (True, 0.52359877559829893, 1.0471975511965979), (False, 0.64350110879328437, 0.9272952180016123), (True, 0.1001674211615598, 1.4706289056333368), (True, 0.1001674211615598, 1.4706289056333368)]
    

    拿第一项(False, 0.1001674211615598, 1.4706289056333368):2&lt;1确实是假的。所以你将1.4706289056333368 作为res 中的第一个值。

    结果是

    >>> res
    [1.4706289056333368, 0.41151684606748806, 0.52359877559829893, 
                0.9272952180016123, 0.1001674211615598, 0.1001674211615598]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      相关资源
      最近更新 更多