del*_*tap 10 python arrays numpy scipy pandas
我有一个包含时间序列数据的numpy数组.我想将该数组分成给定长度的相等分区(如果它的大小不同,可以删除最后一个分区),然后计算每个分区的平均值.
我怀疑有这样的numpy,scipy或pandas功能.
例:
data = [4,2,5,6,7,5,4,3,5,7]
Run Code Online (Sandbox Code Playgroud)
对于bin大小为2:
bin_data = [(4,2),(5,6),(7,5),(4,3),(5,7)]
bin_data_mean = [3,5.5,6,3.5,6]
Run Code Online (Sandbox Code Playgroud)
对于bin大小为3:
bin_data = [(4,2,5),(6,7,5),(4,3,5)]
bin_data_mean = [7.67,6,4]
Run Code Online (Sandbox Code Playgroud)
Joe*_*ton 19
只需使用reshape然后mean(axis=1).
作为最简单的例子:
import numpy as np
data = np.array([4,2,5,6,7,5,4,3,5,7])
print data.reshape(-1, 2).mean(axis=1)
Run Code Online (Sandbox Code Playgroud)
更一般地说,当它不是偶数倍时,我们需要做这样的事情来删除最后一个bin:
import numpy as np
width=3
data = np.array([4,2,5,6,7,5,4,3,5,7])
result = data[:(data.size // width) * width].reshape(-1, width).mean(axis=1)
print result
Run Code Online (Sandbox Code Playgroud)
由于您已经有一个numpy数组,为了避免for循环,您可以使用reshape并将新维度视为bin:
In [33]: data.reshape(2, -1)
Out[33]:
array([[4, 2, 5, 6, 7],
[5, 4, 3, 5, 7]])
In [34]: data.reshape(2, -1).mean(0)
Out[34]: array([ 4.5, 3. , 4. , 5.5, 7. ])
Run Code Online (Sandbox Code Playgroud)
实际上,如果大小可data被整除,这将起作用n.我会编辑一个修复程序.
看起来Joe Kington 有一个可以解决这个问题的答案.
尝试使用标准Python(NumPy不是必需的).假设Python 2.x正在使用中:
data = [ 4, 2, 5, 6, 7, 5, 4, 3, 5, 7 ]
# example: for n == 2
n=2
partitions = [data[i:i+n] for i in xrange(0, len(data), n)]
partitions = partitions if len(partitions[-1]) == n else partitions[:-1]
# the above produces a list of lists
partitions
=> [[4, 2], [5, 6], [7, 5], [4, 3], [5, 7]]
# now the mean
[sum(x)/float(n) for x in partitions]
=> [3.0, 5.5, 6.0, 3.5, 6.0]
Run Code Online (Sandbox Code Playgroud)
小智 5
我刚刚编写了一个函数,将其应用于您想要的所有数组大小或维度。
func是要应用于 bin 的函数(np.max 表示 maxpooling,np.mean 表示平均值...)
def binArray(data, axis, binstep, binsize, func=np.nanmean):
data = np.array(data)
dims = np.array(data.shape)
argdims = np.arange(data.ndim)
argdims[0], argdims[axis]= argdims[axis], argdims[0]
data = data.transpose(argdims)
data = [func(np.take(data,np.arange(int(i*binstep),int(i*binstep+binsize)),0),0) for i in np.arange(dims[axis]//binstep)]
data = np.array(data).transpose(argdims)
return data
Run Code Online (Sandbox Code Playgroud)在你的情况下它将是:
data = [4,2,5,6,7,5,4,3,5,7]
bin_data_mean = binArray(data, 0, 2, 2, np.mean)
Run Code Online (Sandbox Code Playgroud)
或者对于大小为 3 的 bin:
bin_data_mean = binArray(data, 0, 3, 3, np.mean)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10331 次 |
| 最近记录: |