Search code examples
pythonpandasnumpyaverage

how do I find the average of this array but only for the values that are not equal to zero in python


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)


Solution

  • 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)