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)
how do I find the average of this array but only for the values that are not equal to zero in python
Asked
Active
Viewed 166 times
3 Answers
2
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)

Chinny84
- 956
- 6
- 16
1
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

Nin17
- 2,821
- 2
- 4
- 14
-
1This is an expensive operation - each element of the raw numpy array needs to be converted to a python object. Better to keep it as an numpy arrray and use its operators. – tdelaney Apr 27 '22 at 22:27
1
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

Heidi Hussein
- 13
- 5