array([1500, 1520, 1540, 1590, 1590, 1600, 1600, 1560, 1560, 1560, 1580, 1520, 1460, 1510, 1520, 1320, 1320, 1300, 1300, 1320, 1320, 1320, 1320, 1300, 1300, 1340, 1300, 1300, 1300, 1400, 1480, 1360, 1420, 1480, 1580, 1530, 1500, 1480, 1480, 1480, 1460, 1540, 1490, 1480, 1480, 1520, 1500, 1460, 1480, 1480, 1500, 1500, 1600, 1540, 1480, 1460, 1560, 1600, 1560, 1600, 1600, 1600, 1620, 1600, 1580, 1600, 1700, 1620, 1620, 1620, 1700, 1700, 1680, 1640, 1620, 1670, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1670, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1600, 1680, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int64)
CodePudding user response:
You can filter the array
arr = np.array([41, 42, 43, 44, 0, 0,0])
arr.mean() # 24.2857
arr[arr != 0].mean() # 42.5
edit: (!= to include negative numbers thanks to @tdelaney)
CodePudding user response:
Here's a simple approach is to just make a copy of the array without the zeros, then calculate the average, this way:
import numpy as np
new_array = array[array!=0] #Create a copy of the array excluding the zeros
avg = np.average(new_array)
And here's another idea that doesn't use any of numpy methods:
count=0
total=0
for number in array:
if number != 0:
total =number #adds the non-zero values together
count =1 #counts the non-zero values
avg= total/count
CodePudding user response:
You can do that with list comprehension and numpy:
import numpy as np
a = np.array([1500, 1520, 1540, 1590, 1590, 1600, 1600, 1560, 1560, 1560, 1580,
1520, 1460, 1510, 1520, 1320, 1320, 1300, 1300, 1320, 1320, 1320, 1320,
1300, 1300, 1340, 1300, 1300, 1300, 1400, 1480, 1360, 1420, 1480,
1580, 1530, 1500, 1480, 1480, 1480, 1460, 1540, 1490, 1480, 1480,
1520, 1500, 1460, 1480, 1480, 1500, 1500, 1600, 1540, 1480, 1460,
1560, 1600, 1560, 1600, 1600, 1600, 1620, 1600, 1580, 1600, 1700,
1620, 1620, 1620, 1700, 1700, 1680, 1640, 1620, 1670, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1670, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1600, 1680, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0], dtype=np.int64)
np.mean([i for i in a if i])
Output:
1508.4810126582279