在python中将两个数组乘以不同的长度

时间:2018-10-18 16:21:43

标签: python arrays numpy vector multiplication

我想知道是否有可能解决此问题。我有这个值:

yf = (0.23561643, 0.312328767,  0.3506849315, 0.3890410958,  0.4273972602,  0.84931506)
z = (4.10592285e-05,  0.0012005020, 0.00345332906,  0.006367483, 0.0089151571,  0.01109750, 0.01718827)

我想使用此功能(折现系数),但由于z和yf之间的长度不同,因此无法使用。

def f(x): 
        res = 1/( 1 + x * yf)
        return res
f(z) 
output: ValueError: cannot evaluate a numeric op with unequal lengths

我的问题是,是否存在解决此问题的方法。大概的输出值为:

res = (0.99923, 0.99892, 0.99837, 0.99802, 0.99763, 0.99175)

任何对此的帮助将是完美的,在此先感谢所有花时间阅读或尝试提供帮助的人。

2 个答案:

答案 0 :(得分:1)

您想将数组广播到较短的那个吗?你可以做到

def f(x): 
    leng = min(len(x), len(yf))
    x = x[:leng]
    new_yf = yf[:leng] # Don't want to modify global variable.
    res = 1/( 1 + x * new_yf)
    return res

它应该可以工作。

答案 1 :(得分:1)

Find the minimum length and iterate. Can also covert to numpy arrays and that would avoid a step of iteration

import numpy as np
yf = (0.23561643, 0.312328767,  0.3506849315, 0.3890410958,  0.4273972602,  0.84931506)
z = (4.10592285e-05,  0.0012005020, 0.00345332906,  0.006367483, 0.0089151571,  0.01109750, 0.01718827)
x=min(len(yf),len(z))

res = 1/( 1 + np.array(z[:x]) * np.array(yf[:x]))

使用numpy.multiply

res = 1/( 1 + np.multiply(np.array(z[:x]),np.array(yf[:x])))