简体   繁体   中英

Average of multi-dimensional array in Python

I have a temperature data that I keep as an array:

temp[month][day][hour][min]

Is there an easy way to get the hourly average of the data, which is the average of all values in the same hour? Similarly, the daily average?

You should be able to use these functions to get the needed averages:

def hourly_average(values, month, day, hour):
  hour_data = values[month][day][hour]
  # extract the values for every minute in the specified hour.
  minute_values = [hour_data[min] for min in xrange(0,60)]
  return sum(minute_values)/60

def daily_average(values, month, day):
  # extract the averages for every hour in the specified day.
  hour_values = [hourly_average(vales,month,day,hour) for hour in xrange(0,24)]
  # the average of the averages of the equally weighted parts is the average 
  # of the thing itself (?).
  return sum(hour_values)/24

You'll be interested in using numpy .

Something like this becomes as simple as:

import numpy

data_as_numpy_array = numpy.array(original_data)

hourly_averages = numpy.average(data_as_numpy_array, 3)

daily_averages = numpy.average(hourly_averages, 2)

In the second two lines, the second argument is the axis along which you wish to average. Here 3 is the axis of the minute data, and two the axis of the hour data.

You may also be interested in installing pylab and ipython. Pylab emulates the graphing/visualisation functionality of Matlab, and ipython is an enhanced interpreter with tab-completion and full command input (and output) history amongst other things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM