N
N
nuclear_skillet210112016-02-23 05:12:52
Python
nuclear_skillet21011, 2016-02-23 05:12:52

How to print the index of a specific value in a multidimensional array in Python?

import numpy as np

def find_index_iin_matrx(grid, row, col): # [row] - ряд, [col] - столбец, [ grid ] - многомерный массив( матрица 5х5 )
          
  mass_el_1 = []
  grid1 = np.array(grid)
  
  for el in grid1.flat: # атрибут flat (numpy) используется при для обработки массива как одномерного
    if el == 1:
      ac = grid1.index(el) # здесь ошибка AttributeError: 'numpy.ndarray' object has no attribute 'index'
      mass_el_1.append(ac)
  print(masvie_index)

Today for the first time I encountered a multidimensional array in python. The task is trivial: to calculate the indices of all non-zero values ​​in the matrix. And then check which of the values ​​are "adjacent":
((1, 0, 0, 1, 0),
(0, 1 , 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
( 0, 0, 1, 0, 0))

unit in the second row, second column: two neighbors with indices (1,1) and (3,3). Can you tell me what code to use to identify them?
Thank you for your attention.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nirvimel, 2016-02-23
@nuclear_skillet21011

1. A numpy array does not have a index().
2. Display all indices of all non-zero elements of grid1:

import numpy


def print_all_non_zero_values(arg):
    print ((numpy.array(arg) > 0).astype(numpy.intc))

3. Counting non-zero neighbors:
import numpy


def count_neighbours(source):
    grid1 = numpy.array(source) > 0
    x_size, y_size = grid1.shape
    grid2 = numpy.zeros((x_size + 2, y_size + 2), dtype=numpy.intc)
    grid2[ :-2,  :-2] += grid1
    grid2[1:-1,  :-2] += grid1
    grid2[2:  ,  :-2] += grid1
    grid2[ :-2, 1:-1] += grid1
    grid2[1:-1, 1:-1] += grid1
    grid2[2:  , 1:-1] += grid1
    grid2[ :-2, 2:  ] += grid1
    grid2[1:-1, 2:  ] += grid1
    grid2[2:  , 2:  ] += grid1
    return (grid2[1:-1, 1:-1] - 1) * grid1

Test:
count_neighbours(((0, 0, 1, 0),
                  (0, 1, 1, 0),
                  (0, 1, 1, 0),
                  (0, 1, 0, 0),))

Result:
array(, dtype=int32)

N
nuclear_skillet21011, 2016-02-26
@nuclear_skillet21011

[ same code ]

def count_neighbours(grid, row, col): # [row] - ряд
                    # [col] - столбец
  mass_el_1 = []
  grid1 = np.array(grid)

  mass8 = [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

  mass3 = [(0,4),(4,4),(4,0),(0,0)]
  
  mass5 = [(1,0),(2,0),(3,0),(0,1),(0,2),(0,3),(1,4),(2,4),(3,4),(4,1),(4,2),(4,3)]
 
  xl = []
  yl = []
  for x in range(grid1.shape[0]):
    for y in range(grid1.shape[1]):
      if grid1[x, y] != 0:
        print (x, y)
        xl.append(x)
        yl.append(y)
        print(xl)
        print(yl)


  listindex = list(zip(xl,yl))
  print(listindex)

  xlll = []
  ylll = []

  neighbours = []
  exepts = []

  for x in range(grid1.shape[0]):
    for y in range(grid1.shape[1]):
      if grid1[x, y] != 0:
              
        for i in listindex:
          print('i: ',i)

          for i1 in mass8:
            print('i1: ',i1)

            if i == i1:
              
              try:
                    
                if  grid1[x-1, y-1] == 1:
                  neighbours.append((x-1, y-1))
                elif grid1[x, y-1] == 1:
                  neighbours.append((x, y-1))
                elif grid1[x+1, y-1] == 1:
                  neighbours.append((x+1, y-1))							
                elif grid1[x+1, y] == 1:
                  neighbours.append((x+1, y))							
                elif grid1[x+1, y+1] == 1:
                  neighbours.append((x+1, y+1))							
                elif grid1[x, y+1] == 1:
                  neighbours.append((x, y+1))							
                elif grid1[x-1, y+1] == 1:
                  neighbours.append((x-1, y+1))							
                elif grid1[x-1, y] == 1:
                  neighbours.append((x-1, y))

              except IndexError :

                exepts.append((x,y))
              
  print(neighbours,"len:",len(neighbours))
  print(exepts,"len:",len(exepts))

count_neighbours(((1, 0, 0, 1, 0),
                  (0, 1, 0, 0, 0),
                  (0, 0, 1, 0, 1),
                  (1, 0, 0, 0, 0),
                  (0, 0, 1, 0, 0),),0,0)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question