在numpy中,对数组或矩阵中的每个元素,进行函数计算

在numpy中,对数组或矩阵中的每个元素,进行函数计算

2019年12月6日 数据分析日记

今天学到了一个利用自建函数,对numpy矩阵种元素进行计算的新招

假设有一个数组或矩阵:
( 0 1 1 0 ) \left( \begin{array}{ccc} 0 & 1 \\ 1 & 0 \\ \end{array} \right) (0110)

需对其中每个元素输入函数:

F ( x ) = 44000 + 165000 × [ 1 − e ( − 0.3 ) x 6 ] F(x) = 44000 + 165000 \times [1 - e^{\frac{(-0.3) x}{6}}] F(x)=44000+165000×[1e6(0.3)x]
那么我们可以创建数据集:

import numpy as np
matrix_test = np.array([[0,1],[1,0]])

并且构造函数:

def function_A(x):
    return (440000 + 165000*(1 - np.exp((-0.3) * x / 6)))

然后直接计算:

function_A(matrix_test)

得到结果:

array([[440000.        , 448047.14495738],
       [448047.14495738, 440000.        ]])

然而,当这个函数变为一个非连续函数时:
F ( x ) = { 0 if x = 0 44000 + 165000 × [ 1 − e ( − 0.3 ) x 6 ] if x ≥ 0 F(x) = \left \{ \begin{array}{ccc}\\ 0 & \textrm{if x = 0}\\ 44000 + 165000 \times [1 - e^{\frac{(-0.3) x}{6}}] & \textrm{if x ≥ 0}\\ \end{array} \right. F(x)={044000+165000×[1e6(0.3)x]if x = 0if x ≥ 0
我们可以构造新的函数:

def function_B(x):
    if x == 0:
        result = float(0)
    else:
        result = 440000 + 165000*(1 - np.exp((-0.3) * x / 6))
    return result

运行时会报错:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-42-0423f1e4de9c> in <module>()
----> 1 function_B(matrix_test)

<ipython-input-41-99e5c180ace1> in function_B(x)
      1 def function_B(x):
----> 2     if x == 0:
      3         result = float(0)
      4     else:
      5         result = 440000 + 165000*(1 - np.exp((-0.3) * x / 6))

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

显然,对于带有if…else这样带条件的函数,并不能直接输入矩阵进行计算。查找numpy文档发现,应通过numpy.vectorize()这个函数函数进行处理(官方文档: https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html )

因此先对function进行向量化处理:

function_vector = np.vectorize(function_B)
function_vector(matrix_test)

得到正确结果:

array([[     0.        , 448047.14495738],
       [448047.14495738,      0.        ]])
  • 31
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值