【问题标题】:Apply a function to numpy array in Python [duplicate]在Python中将函数应用于numpy数组[重复]
【发布时间】:2018-08-23 23:38:25
【问题描述】:

我正在尝试将一个函数与几个参数一起应用于 numpy 数组的每个元素。

def wcdf(u, A, k):
    if(u > 0):
        y=(1 - np.exp(-(u/A)**(k)));
        return y
    else:
        return(0)

我不知道我错过了什么,但只要数组有 0,它就会为每个元素返回 0

f=np.vectorize(wcdf)
u=f(np.array([1,2]),10,2);
print(u)

结果:[0.00995017 0.03921056]

上面的工作正常,但是当我有一个零时:

u=f(np.array([0,2]),10,2);
print(u)

结果:[0 0]

谁能指出我做错了什么!!!!

谢谢

【问题讨论】:

  • 你的weibull_cumulated_freq是什么?
  • 函数wcdf中,如果u是一个数组,则不能做if(u>0)。它应该返回错误ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
  • 对不起,我已经更新了代码。
  • @Siladittya, wcdf, u 不是数组。
  • 这个answer 似乎可以解决您的问题(在此点赞)。加otypesnp.vectorize(wcdf, otypes=[np.float])

标签: python numpy scipy


【解决方案1】:

尝试将数组传递为np.float32

import numpy as np
def wcdf(U, A, k):
    return np.array([1 - np.exp(-(u/A)**(k)) if u >0 else 0 for u in U])


u=wcdf(np.array([0,2],dtype=np.float32),10,2);
print(u)

我的结果:

[ 0. 0.03921056]

使用np.vectorize的方法

import numpy as np
def wcdf(u, A, k):
    return 1 - np.exp(-(u/A)**(k)) if u >0 else 0

f = np.vectorize(wcdf,otypes=[float])
u=f(np.array([0,2],dtype=np.float32),10,2);
print(u)

结果:

[ 0. 0.03921056]

您已将otypes 添加为float

【讨论】:

  • 谢谢。它有帮助
猜你喜欢
  • 2019-07-25
  • 2017-08-20
  • 1970-01-01
  • 2014-04-20
  • 2020-08-16
  • 2020-02-24
  • 2022-11-25
  • 2017-07-10
  • 2016-08-19
相关资源
最近更新 更多