将 python 中两个长度不同的数组相乘
Multiplying two arrays in python with different lenghts
我想知道是否可以解决这个问题。我有这个值:
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)
任何帮助都将是完美的,我想提前感谢所有花 his/her 时间阅读它或尝试提供帮助的人。
是否要将数组广播到较短的那个?你可以这样做
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
它应该可以工作。
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])))
我想知道是否可以解决这个问题。我有这个值:
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)
任何帮助都将是完美的,我想提前感谢所有花 his/her 时间阅读它或尝试提供帮助的人。
是否要将数组广播到较短的那个?你可以这样做
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
它应该可以工作。
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])))