繁体   English   中英

如何用另一维替换n维数组的一维?

[英]How to replace one dimension of an n-dimensional array with another?

我有一个形状为(4, 30, 13, 7000)的 numpy 数组。 这是实验数据。 前三个维度代表实验条件。 最后一个维度表示前三个维度的每个组合的 7000 毫秒。 所以数组中有 1560 个 7000ms 的列表。

我已经构建了一个滑动窗口平均值 function 我在每 7000 毫秒列表上执行一次:

def windowed_mean(4D_list)

    for trial in 4D_list:
        for neuron in trial:
            for timebin in neuron:
                chunk = timebin #chunk equals every 7000ms timespan. 
                window_size = 250 #ms
                i = 0
                while i < len(chunk) - window_size + 1: #sliding window average
                    window = chunk[i : i + window_size] #generates window
                    window_average = sum(window) / window_size #takes window average
                    moving_average.append(window_average) #appends window average to #moving_average list 
                    i += 25 #step size
    
                stored_averages.append(window_average)
                moving_average.clear()

    
    print(len(stored_averages)) #this list contains the stored windowed averages in order

我的问题是,如何用存储在stored_averages中的新窗口平均值替换原始数组的第四维(时间)? 理想情况下,我希望得到一个形状为 4、30、13、271、271 的新数组4, 30, 13, 271, 271因为这是我每 7000 毫秒试验获得的窗口数。

如果您想要移动平均线,请查看scipy.ndimage.convolve1d 滑动的 window 只是与适当宽度和高度的框 function 进行卷积。

你正在寻找类似的东西

def windowed_mean(arr, n, axis=-1):
    box = np.full(n, 1.0 / n)
    return ndimage.convolve1d(arr, box, axis)

这将返回一个与原始大小相同的数组。 你可能想要一些不包括部分卷积元素的东西,所以你可以从左边修剪(n - 1) // 2和从右边修剪n // 2 使用 integer 这样的除法可确保修剪对于偶数和奇数 windows 都是正确的:

    return  ndimage.convolve1d(arr, box, axis)[..., (n - 1) // 2:-(n // 2)]

您可以使用像np.convolve这样的一维卷积器进行相同的卷积。 这将要求您的数据进行排列,以便您正在卷积的维度是连续的。 这很可能是这种情况,因为 numpy 默认使用 C 顺序:

def windowed_mean(arr, n):
    box = np.full(n, 1.0 / n)
    conv = np.convolve(arr.ravel(), box)
    return conv[n - 1:].reshape(arr.shape)[..., :1 - n]

要对非最后一个维度进行操作,您必须将感兴趣的轴移动到最后。 请记住,在这种情况下, ravel会复制数据:

def windowed_mean(arr, n, axis=-1):
    box = np.full(n, 1.0 / n)
    a = np.moveaxis(arr, axis, -1).ravel()
    conv = np.convolve(a, box)
    conv = conv[n - 1:].reshape(arr.shape)[..., :1 - n]
    return np.moveaxis(conv, -1, axis)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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