简体   繁体   English

如何更改只有 0 和 1 的 2d numpy 数组中所有 1 的索引?

[英]How to change the index of all the 1 in an 2d numpy array which only has 0s and 1s?

I have a 2d numpy array(arr) which only has 0s and 1s.我有一个只有 0 和 1 的 2d numpy 数组(arr)。

For example, a 2d numpy array in shape(h,w).例如,形状为 (h,w) 的二维 numpy 数组。

I want to resize the array to shape(h // scale, w // scale), and I need to keep all the 1s.我想将数组的大小调整为 shape(h // scale, w // scale),并且我需要保留所有的 1。

# arr is a 2d numpy array
h, w = arr.shape
h_new, w_new = h // scale, w // scale
arr_new = np.zeros((h_new, w_new))
for i in range(h):
    for j in range(w):
        if arr[i, j] == 1:
            arr_new[i // scale, j // scale] = 1

For example, a 2d array like this, and scale=2:例如,像这样的二维数组,并且 scale=2:

[
    [0,0,0,0],
    [0,1,0,0],
    [1,0,0,1],
    [0,0,0,1]
]

After runnung the code, arr_new will be:运行代码后, arr_new 将是:

[
    [1,0],
    [1,1]
]

the change of all the 1s' coordinates:所有1s坐标的变化:

(1,1) -> (0,0)
(2,0) -> (1,0)
(2,3) -> (1,1)
(3,3) -> (1,1)

Is there a better way to do this?有一个更好的方法吗?

Thanks.谢谢。

Just reshape the array by splitting each dimension to grid (SIZE // SCALE, SCALE) .只需通过将每个维度拆分为网格(SIZE // SCALE, SCALE)来重塑数组。 Next reduce all dimensions of size SCALE using max() to let 1 dominate the SCALExSCALE cell.接下来使用max()减少大小 SCALE 的所有维度,让1支配 SCALExSCALE 单元格。

arr.reshape(h//scale, scale, w // scale, scale).max(axis=(1,3))

Note that this solution requires shape of array to be multiplicity os (scale, scale) .请注意,此解决方案要求array的形状为多重性 os (scale, scale)

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

相关问题 numpy 二维数组的所有组合,其中填充了 0 和 1 - All combinations of a numpy 2d array filled with 0s and 1s 在仅包含1和0的数组中找到第一个1的索引,所有0都在数组的左侧,所有1都在右侧? - Find the index of the first 1 in an array which contains only 1s and 0s, all the 0s being to the left side of the array, and all the 1s to the right? 仅包含 0 和 1 的二维矩阵 - python - 2D matrix containing only 0s and 1s - python 如何生成大小为 41003 的 0 和 1 数组,并且 1 的数量应该仅为 100? - how to generate an array of 0s and 1s of size 41003 and number of 1s should be 100 only? 在2D列表中互换0和1的最快方法 - Fastest way of interchanging 0s and 1s in a 2D list 按顺序指定数量为1和0的Numpy数组 - Numpy array of specified number of 1s and 0s in order Numpy 数组制作 1 和 0 的“Z”? - Numpy array to make a 'Z' of 1s and 0s? 如何获得仅由 0 和 1 组成的 3D 矩阵的 3D 坐标 - How can I get 3D coordinates of a 3D matrix consisting of only 0s and 1s Numpy:给定向量0和1s,如何有效地使用Numpy函数基于第一个数组的0/1值来操纵另一个数组中的值? - Numpy: given a vector of 0s and 1s, how to efficiently use Numpy functions manipulate values in another array, based on 0/1 value of first array? 将数组转换为0和1 - Converting an array to 0s and 1s
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM