[英]Numpy array 15min values - hourly mean values
I have the following situation: 我有以下情况:
A numpy array 一个numpy数组
x = np.array([12,3,34,5...,])
where every entry corresponds to a simulation result (time-step 15min). 其中每个条目对应一个模拟结果(时间步长15分钟)。
Now I need the mean hourly value (mean value of first 4 elements, then next 4, etc.) stored in a new numpy array. 现在,我需要将平均小时值(前4个元素的均值,然后是下4个元素的均值)存储在新的numpy数组中。 Is there a very simple method to accomplish this?
有没有很简单的方法来完成此任务?
To handle arrays whose size may not be a multiple of 4, copy x
into a new array, tmp
, whose size is a multiple of 4: 要处理大小可能不是4的倍数的数组,
tmp
x
复制到新的数组tmp
,其大小是4的倍数:
tmp = np.full((((x.size-1) // 4)+1)*4, dtype=float, fill_value=np.nan)
tmp[:x.size] = x
Empty values are represented by nan
. 空值用
nan
表示。 Then you can reshape and use nanmean
to compute the mean for each row. 然后,您可以重塑
nanmean
并使用nanmean
计算每行的均值。 np.nanmean
is like np.mean
except that it ignores nan
s: np.nanmean
类似于np.mean
只是它忽略了nan
s:
x = np.array([12,3,34,5,1])
tmp = np.full((((x.size-1) // 4)+1)*4, dtype=float, fill_value=np.nan)
tmp[:x.size] = x
tmp = tmp.reshape(-1, 4)
print(np.nanmean(tmp, axis=1))
prints 版画
[ 13.5 1. ]
If you have pandas installed, then you could build a timeseries and group by a time interval: 如果安装了熊猫 ,则可以建立时间序列并按时间间隔进行分组:
import numpy as np
import pandas as pd
x = np.array([12,3,34,5,1])
s = pd.Series(x, index=pd.date_range('2000-1-1', periods=x.size, freq='15T'))
result = s.groupby(pd.TimeGrouper('1H')).mean()
print(result)
yields 产量
2000-01-01 00:00:00 13.5
2000-01-01 01:00:00 1.0
Freq: H, dtype: float64
N = 4
mod_ = x.size % N
x1 = np.pad(x.astype(float), (0, (mod_ > 0) * (N - mod_)), 'constant', constant_values=(np.nan,))
x2 = np.reshape(x1, (int(x1.size/4), 4))
x3 = np.nanmean(x2, axis=1)
print(x3)
Here is another solution: 这是另一种解决方案:
your input: 您的输入:
In [11]: x = np.array([12, 3, 34, 5, 1, 2, 3])
taking every 4 elements in b 取b中的每4个元素
In [12]: b = [x[n:n+4] for n in range(0, len(x), 4)]
create new empty list to append results 创建新的空列表以追加结果
In [13]: l = []
In [14]: for i in b:
....: l.append(np.mean(i))
....:
In [15]: l
Out[15]: [13.5, 2.0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.