[英]Is there a way to find the sum of the last n and first n elements in a 2D array using only NumPy?
Lets say that n is a variable and I use a simple matrix example.假设n是一个变量,我使用一个简单的矩阵示例。
import numpy as np
n = 2
matrix = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
desired_output = np.array([[nan, nan, 10, 15, 20, 25, 30, 35, nan, nan],
[nan, nan, 10, 15, 20, 25, 30, 35, nan, nan]])
So desired_output[i] = sum of elements in the interval matrix[i - n, i + n] both inclusive.所以desired_output[i] = 区间矩阵[i - n, i + n]中的元素之和,包括两者。 Is there a way to do this using NumPy and without python iteration?有没有办法使用 NumPy 而没有 python 迭代来做到这一点? The numbers in the array can be arbitrary.数组中的数字可以是任意的。
You can use one of my absolute favorite things to be added to numpy in 1.20: numpy.lib.stride_tricks.sliding_window_view
您可以使用我最喜欢的东西之一在 1.20 中添加到 numpy: numpy.lib.stride_tricks.sliding_window_view
import numpy as np
matrix = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
n = 2
First, apply the sliding window view:首先,应用滑动 window 视图:
window_size = 2 * n + 1
arr = np.lib.stride_tricks.sliding_window_view(matrix, window_size, axis=1)
Then sum it on the last axis:然后在最后一个轴上求和:
arr = arr.sum(axis=2)
This gives you:这给了你:
>>> arr
array([[10, 15, 20, 25, 30, 35],
[10, 15, 20, 25, 30, 35]])
To the best of my knowledge there's no integer NaN in numpy so your integer/nan output is impossible.据我所知,numpy 中没有 integer NaN 所以你的整数/nan output 是不可能的。 If you want floats you can pad easily with nans though:如果你想要浮动,你可以很容易地用 nans 填充:
arr_padded = np.full((arr.shape[0], arr.shape[1] + 2 * n), np.nan)
arr_padded[:, n:-1 * n] = arr
>>> arr_padded
array([[nan, nan, 10., 15., 20., 25., 30., 35., nan, nan],
[nan, nan, 10., 15., 20., 25., 30., 35., nan, nan]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.