python - 对包裹的 2D 数组中的子数组进行高效 Numpy 采样

标签 python arrays numpy

我有一个 4x4 数组,想知道是否有一种方法可以在任意位置从其中随机采样 2x2 正方形,从而允许正方形在到达边缘时环绕。

例如:

>> A = np.arange(16).reshape(4,-1)
>> start_point = A[0,3]

start_point = 3

正方形将是[[15, 12], [3,0]]

最佳答案

我已经概括了(有点......)我的答案,允许矩形输入数组 甚至是矩形随机样本

def rand_sample(arr, nr, nc):
    "sample a nr x nc submatrix starting from a random element of arr, with wrap"
    r, c = arr.shape
    i, j = np.random.randint(r), np.random.randint(c)
    r = np.arange(i, i+nr) % r
    c = np.arange(j, j+nc) % c
    return arr[r][:,c]

您可能想检查 arr 是否是一个二维数组

关于python - 对包裹的 2D 数组中的子数组进行高效 Numpy 采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30235358/

相关文章:

python - wxPython检查c++部分是否被删除

ios - 如何使用 ImageView 从图像数组创建随机图像生成器?

java - 比较数组java

python - 计算numpy中值之间的平均加权欧氏距离

python - 不使用嵌套循环读取文件和文件夹

python - 使用 Python 覆盖属性

python - OpenCV(4.2.0) (-206 :Bad flag (parameter or structure field)) Unrecognized or unsupported array type in function 'cvGetMat'

java - 打印居中对齐的二维数组

python - 重新排列 numpy 数组

python-3.x - 根据其他列的最大值选择列中的值