【问题标题】:ValueError when converting a loop to vectorized format using np.where使用 np.where 将循环转换为矢量化格式时出现 ValueError
【发布时间】:2019-05-22 01:20:33
【问题描述】:

在 np.where 条件中使用 min、max 函数时出现以下错误。

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我想将“for”循环转换为更快的计算,因此我尝试使用“np.where”函数切换我的计算。

原始工作循环代码

for p in range (1,len(curve_details)):                       
      curve_details.loc[p,'coupon_after']=max(floor,min(ceiling, 
      curve_details.loc[p-1,'coupon_after']                                                       
      + max(move_cap_down, min(move_cap_up,                                                          
      curve_details.loc[p,'coupon_before']                                                          
      -curve_details.loc[p-1,'coupon_after']))))

我正在尝试的新代码

curve_details['coupon_after']=np.where(curve_details.index>0,
                             max(floor,min(ceiling, 
                             curve_details.loc[curve_details.index- 
                             1,'coupon_after'] + max(move_cap_down, 
                             min(move_cap_up,                       
                  curve_details.loc[curve_details.index,'coupon_before']
                              -curve_details.loc[curve_details.index- 
                             1,'coupon_after'])))),int_rate)

我想加快我的 for 循环,因此已切换到 'np.where' 函数。我现在可以在我的代码中进行哪些更改以消除值错误?

【问题讨论】:

    标签: pandas numpy for-loop


    【解决方案1】:

    您不能在数组和标量上使用裸 maxmin。尝试使用np.clip。由于我没有示例数据,因此无法在您的代码中显示它。但是一个简单的例子:

    x = np.arange(10)
    cap = 6
    low = 3
    np.clip(x, low, cap)
    
    # is equivalent to (and much better than):
    np.array([max(low, min(cap, i)) for i in x])    
    

    【讨论】:

    • 我找到了另一个函数 np.fmax 和 np.fmin,它们给了我最大和最小的输出。但是,我无法正确构造我的输出,因为在执行 np.where 时我首先需要当前索引值,并且基于需要 (Index-1) 中的前一行值。我的 curve_details.loc[curve_details.index- 1,'coupon_after'] 语法在执行 np.where 时给了我一个系列,而不仅仅是前一行的值。
    猜你喜欢
    • 2023-02-05
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2019-02-24
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多