【问题标题】:Multiplying two arrays in python with different lenghts在python中将两个不同长度的数组相乘
【发布时间】:2018-10-18 16:21:42
【问题描述】:

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

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)

对此的任何帮助都是完美的,我要提前感谢所有花时间阅读或尝试提供帮助的人。

【问题讨论】:

  • 你能解释一下你想对 z 中的额外值发生什么吗?你只是希望它被丢弃吗?

标签: python arrays numpy vector multiplication


【解决方案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

它应该可以工作。

【讨论】:

  • 使用min(len(x), len(yf))
【解决方案2】:
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])))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2021-07-19
    • 2014-03-30
    • 2012-04-27
    相关资源
    最近更新 更多