Extract each row of non-zero array blocks from the two-dimensional array and set 1

import numpy as np
import copy
import itertools
import operator
L = np.array([[0,0,3,2,1], [0, 0, 0, 2, 1], [1, 1, 0, 0, 5], [1, 0, 0, 0, 0]])
L1 = copy.deepcopy(L)
L2 = copy.deepcopy(L)
[a, b] = np.shape(L)
L3 = np.zeros((a, b))
row_nonzeros_index_list = []
for i in range(a):
    row_array = L[i]
    row_nonzeros_index = np.where(row_array != 0)
    L1[i][row_nonzeros_index] = 1
    row_nonzeros_index_array = [[i for i, value in it] for key, it in itertools.groupby(enumerate(L1[i]), key=operator.itemgetter(1)) if key != 0]
    row_nonzeros_index_list.append(row_nonzeros_index_array)
    number_index = len(row_nonzeros_index_array)
    for j in range(len(row_nonzeros_index_array)):
        number_L2 = row_nonzeros_index_array[j]
        if np.size(number_L2) > 1:
            mean_value = np.mean(np.array(L2[i][number_L2]))
            min_value_index = (np.abs(L2[i][number_L2] - mean_value)).argmin()
            relativity_index = number_L2[min_value_index]
            L3[i][relativity_index] = 1
        else:
            L3[i][number_L2] = 1

print('CC' , L3)

This code can extract each row of non-zero number blocks in the array L, and calculate the average value of each number block, and compare which number is closest to the original number block after calculating the average value. Then place 1 at the nearest number index, and if there are multiple number blocks in each row, calculate them separately.

 

Guess you like

Origin blog.csdn.net/kakangel/article/details/84978726