【问题标题】:Clean way to return default when taking minimum of empty NumPy array采用最少的空 NumPy 数组时返回默认值的干净方法
【发布时间】:2022-01-19 09:42:54
【问题描述】:

我有两个数组,一个保存一系列年份,另一个保存一些数量。我想研究每年数量翻倍需要多长时间。

为此我写了这段代码:

years = np.arange(2020, 2060)
qma = np.array([8.00000000e+13, 8.14928049e+13, 8.30370113e+13, 8.46353044e+13,
       8.62905581e+13, 8.80058517e+13, 8.97844887e+13, 9.16300175e+13,
       9.35462542e+13, 9.55373083e+13, 9.76076116e+13, 9.97619497e+13,
       1.02005499e+14, 1.04343864e+14, 1.06783128e+14, 1.09329900e+14,
       1.11991375e+14, 1.14775397e+14, 1.17690539e+14, 1.20746183e+14,
       1.23952624e+14, 1.27321176e+14, 1.30864305e+14, 1.34595778e+14,
       1.38530838e+14, 1.74048570e+14, 1.92205500e+14, 2.14405932e+14,
       2.42128686e+14, 2.77655470e+14, 3.24688168e+14, 3.89624819e+14,
       4.84468500e+14, 6.34373436e+14, 9.74364148e+14, 2.33901669e+15,
       1.78934647e+16, 4.85081278e+20, 8.63469750e+21, 2.08204297e+22])

def doubling_year(idx):
      try:
        return years[qma >= 2*qma[idx]].min()
      except ValueError:
        return np.nan
    
years_until_doubling = [doubling_year(idx) - years[idx] 
                        for idx in range(len(years))]

这正如我所期望的那样工作,但是必须为本质上是单线的东西定义一个命名函数感觉不对。有没有更简洁、更成功的方法来复制这种行为?

【问题讨论】:

  • 你研究过np.amin的文档吗?

标签: python numpy minimum


【解决方案1】:

似乎我们可以将最后一年排除在循环之外,而不是最小化 True 的索引,而是计算 doubling_year 中的 False 数量:

years_until_doubling = years[-1] + 1 - np.array([(qma >= 2*q).sum()+y for q, y in zip(qma, years)])

【讨论】:

    【解决方案2】:

    对于系列中的每一年,可以通过广播计算出数量是原始数量两倍或更多的年数。然后,您只需从系列中剩余的年数中减去该数字,然后将 0 替换为 np.nan

    In [426]: n_doubled = np.sum(qma[None, :] >= 2*qma[:, None], axis=1)
    
    In [427]: n_doubled
    Out[427]: 
    array([15, 15, 15, 15, 15, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 12, 12,
           12, 12, 12, 11, 11, 11, 11, 11,  9,  9,  8,  8,  7,  6,  6,  6,  5,
            5,  4,  3,  2,  1,  0])
    
    In [428]: np.where(n_doubled, np.arange(len(years), 0, -1) - n_doubled, np.nan)
    Out[428]: 
    array([25., 24., 23., 22., 21., 21., 20., 19., 18., 17., 17., 16., 15.,
           14., 13., 13., 12., 11., 10.,  9.,  9.,  8.,  7.,  6.,  5.,  6.,
            5.,  5.,  4.,  4.,  4.,  3.,  2.,  2.,  1.,  1.,  1.,  1.,  1.,
           nan])
    

    【讨论】:

      猜你喜欢
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2010-09-21
      相关资源
      最近更新 更多