Вы можете использовать np.where
indices = np.where((distance_matrix <= radius) & (distance_matrix != 0))
row_col_vals = list(zip(*indices, distance_matrix[indices])) # gives you a list or (row, col, value) tuples
Пример, если radius = 5
и
distance_matrix = np.array([[2, 6], [0, 3]])
, то
row_col_vals = [(0, 0, 2), (1, 1, 3)]
Для записи в файл:
f = open('contact.txt', 'w')
for row, col, val in row_col_vals:
print(row, col, val, file=f)
f.close()
HTH.