二维数组中提取每行非零数组块并置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)

这个代码能够将数组L中的每行非零数块提取出来,并对每个数块进行求均值,求均值之后比较与原数块中的哪个数最为接近。然后在最接近的数索引处置1,如果每行中有多个数块,则分别进行计算。

猜你喜欢

转载自blog.csdn.net/kakangel/article/details/84978726