Home > Net >  Seeking missing element in an array in Python
Seeking missing element in an array in Python

Time:07-01

I have an array I with shape=(10,2). I want to probe this array for missing j=1. By missing, I mean there are no indices with j=1. As is evident from I, there are indices with j=2,3,4,5,6,7.

For the purpose of notation, in [0,3], i=0,j=3.

import numpy as np

I=np.array([[0, 3],
       [1, 2],
       [1, 4],
       [2, 5],
       [3, 4],
       [4, 5],
       [4, 6],
       [5, 7],
       [6, 7]])

The expected output is

Missing_j=[1]

CodePudding user response:

If you want to check single index then you can use code from @ArrowRise comment.

if 1 not in I[:,1]: return '1 is missing'

If you want to get all missing indexes then you can use set() for this.

You can convert second column to set

set1 = set(I[:,1])

and generate set with all expected indexes

max_j = max(I[:,1])

set2 = set( range(1, max_j 1) )

And later you can do

missing_j = set2 - set1

Full working example - I added [6, 10] to have more missing indexes.

import numpy as np

I = np.array([
    [0, 3],
    [1, 2],
    [1, 4],
    [2, 5],
    [3, 4],
    [4, 5],
    [4, 6],
    [5, 7],
    [6, 7],
    [6, 10],    
])

set1 = set( I[:,1] )

max_j = max(I[:,1])
set2 = set( range(1, max_j 1) )

missing_j = sorted( set2 - set1 )

print( missing_j )

Result:

[1, 8, 9]
  • Related