删除 n 维 numpy 数组的边界

问题描述 投票:0回答:2

我正在尝试用

False
替换我的n维数组边界的所有值。到目前为止,我已经看到 numpy 提供了
np.pad
允许我使用任意数组在所有维度上增长数组。有没有等价物做相反的事情,通过切割边界来“缩小”阵列?

这是我想扩展到任意维度的 2D 示例:

import numpy as np

nd_array = np.random.randn(100,100)>0   # Just to have a random bool array, but the same would apply with floats, for example

cut_array = nd_array[1:-1, 1:-1]   # This is what I would like to generalize to arbitrary dimension

padded_array = np.pad(cut_array, pad_width=1, mode='constant', constant_values=False)

当然,如果有更简单的方法来更改任意维度的边界值,那也将不胜感激。

python numpy multidimensional-array numpy-ndarray
2个回答
0
投票

您可以使用

np.delete
删除最后一列(示例中的索引 99)。

import numpy as np

nd_array = np.random.randn(100, 100) > 0

cut_array = np.delete(nd_array, 99, 1) # Delete 100th column (index 99)

padded_array = np.pad(cut_array, pad_width=1, mode='constant', constant_values=False)

0
投票

我不会使用先裁剪再填充的方法,因为这样会移动很多内存。

相反,我会明确地将边界索引设置为所需的值:

import numpy as np

nd_array = np.random.randn(100,100) > 0

# Iterate over all dimensions of `nd_array`
for dim in range(nd_array.ndim):
    # Make current dimension the first dimension
    array_moved = np.moveaxis(nd_array, dim, 0)
    # Set border values in the current dimension to False
    array_moved[0] = False
    array_moved[-1] = False
    # We do not even need to move the current dimension
    # back to its original position, as `np.moveaxis()`
    # provides a view into the original data, thus by
    # altering the values of `array_moved`, we also
    # alter the values of `nd_array`. So we are done.

注意

np.moveaxis()
是一个非常便宜的操作,因为它只调整数组的步幅(在我们的例子中产生
array_moved
),所以没有实际的数组数据被移动。

© www.soinside.com 2019 - 2024. All rights reserved.