【问题标题】:Python combining two variable statements into one for numpy functionsPython将两个变量语句组合成一个用于numpy函数
【发布时间】:2020-02-22 23:56:25
【问题描述】:

我有一个函数:

import numpy as np, random

def simulation(low, high, num_pairs):
    c = np.round(np.random.uniform(low, high, num_pairs), 2)
    n = np.round((0.4*c-0.8), 2) # calculate rounded value
    n = np.where(n < 0, 0, n) # if negative `n`, make zero, else `n`
    return list(zip(c, n))

调用这个:

c_n_pairs = simulation(0, 15, 10)
print(*c_n_pairs, sep = "\n")

输出:

(5.69, 1.48)
(11.33, 3.73)
(7.16, 2.06)
(2.93, 0.37)
(8.47, 2.59)
(12.82, 4.33)
(12.84, 4.34)
(7.12, 2.05)
(7.11, 2.04)
(0.07, 0.0)

我有什么工作,但我想知道这两个 n 语句是否可以合并为一个。

    n = np.round((0.4*c-0.8), 2) # calculate rounded value
    n = np.where(n < 0, 0, n) # if negative `n`, make zero, else `n`

【问题讨论】:

  • 对,我陷入了几种不同的想法之中,没有想通。

标签: python


【解决方案1】:

您可以使用np.maximum 获取数组的元素最大值。 这允许您检查每个元素是否小于零,如果是这种情况,则将其替换为零,与np.where 完全相同。

def simulation(low, high, num_pairs):
    c = np.round(np.random.uniform(low, high, num_pairs), 2)
    n = np.maximum(np.round((0.4*c-0.8), 2), 0)
    return list(zip(c, n))

【讨论】:

  • np.zeros(c.size) 已冗余 0 已足够
猜你喜欢
  • 1970-01-01
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 2014-03-20
  • 2022-01-08
相关资源
最近更新 更多