給定的2x3陣列,我要計算在axis=0
的平均水平,但只考慮那些值大於0條件與平均numpy的
所以給出的陣列
[ [1,0],
[0,0],
[1,0] ]
我想要的輸出要
# 1, 0, 1 filtered for > 0 gives 1, 1, average = (1+1)/2 = 1
# 0, 0, 0 filtered for > 0 gives 0, 0, 0, average = 0
[1 0]
我當前的代碼是
import numpy as np
frame = np.array([ [1,0],
[0,0],
[1,0] ])
weights=np.array(frame)>0
print("weights:")
print(weights)
print("average without weights:")
print((np.average(frame, axis=0)))
print("average with weights:")
print((np.average(frame, axis=0, weights=weights)))
這給了我
weights:
[[ True False]
[False False]
[ True False]]
average without weights:
[ 0.66666667 0. ]
average with weights:
Traceback (most recent call last):
File "C:\Users\myuser\project\test.py", line 123, in <module>
print((np.average(frame, axis=0, weights=weights)))
File "C:\Users\myuser\Miniconda3\envs\myenv\lib\site-packages\numpy\lib\function_base.py", line 1140, in average
"Weights sum to zero, can't be normalized")
ZeroDivisionError: Weights sum to zero, can't be normalized
我不明白這個錯誤。我在做什麼錯了,我怎麼能得到沿axis=0
沿大於零的所有值的平均值?謝謝!
'0,0,0過濾爲> 0產生0,0,0' ......不,它不需要。你能否更準確地描述你如何處理沒有找到積極因素的情況?結果應該總是0嗎?結果應該是所有元素的平均值嗎?是否應該計算一些其他的價值? – user2357112
加權平均值計算爲平均數和權重的乘積之和除以權重之和。由於第二列的權重加起來爲0(所有三個都是「假」),所以這種劃分是不可能的。 – DyZ
和對發佈的解決方案的反饋? – Divakar