【问题标题】:Formating numpy arrays to find the sum betyween 2 values Python格式化numpy数组以查找2个值Python之间的总和
【发布时间】:2021-06-10 22:02:00
【问题描述】:

我正在尝试将以下值修改为预期值。下面的函数旨在总结limits 的两个连续元素之间的所有值。没有一个值在0 and 2Numbers 之间,所以结果是0。但是2 and 5 之间的值是3,4Numbers 内,所以结果是3+4=7。该功能已从问​​题中获得:issue

def formating(a, b):
    
    # Formating goes here
    x = np.sort(b);
    # digitize
    l = np.digitize(a, x)
    # output:
    result = np.bincount(l, weights=a)
    return result

Numbers = np.array([3, 4, 5, 7, 8, 10,20])
limit1 = np.array([0, 2 , 5, 12, 15])
limit2 = np.array([0, 2 , 5, 12])
limit3 = np.array([0, 2 , 5, 12, 15, 22])

result1= formating(Numbers, limit1)
result2= formating(Numbers, limit2)
result3= formating(Numbers, limit3)

电流输出

result1:  [ 0.  0.  7. 30.  0. 20.] 
result2:  [ 0.  0.  7. 30. 20.] 
result3:  [ 0.  0.  7. 30.  0. 20.]

想要的输出:

result1:  [ 0.  7. 30.  0.] 
result2:  [ 0.  7. 30. ] 
result3:  [ 0.  7. 30.  0. 20.]

【问题讨论】:

  • 请解释这个问题,因为不清楚您要做什么
  • 哪个位很难回忆,它在Numbers 中一次通过 2 个元素,例如 0 和 2。limit1 - 3 中的第一个和第二个元素。如果在 0 和 2 之间没有任何值,因为 Numbers 的所有元素都大于 2。它给出 0 作为结果。如果Numbers 值在范围内,那么它将把所有Numbers 元素加起来。希望这更清楚。

标签: python arrays function numpy sum


【解决方案1】:

所以把最后的数字垃圾箱扔掉。

result1 = result1[1:len(limit1)]
result2 = result2[1:len(limit2)]
result3 = result3[1:len(limit3)]

或者,为了更智能的结果,结束函数:

    result = np.bincount(1, weights=a)
    return result[1:len(b)]

【讨论】:

猜你喜欢
  • 2021-06-11
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多