Home > OS >  How can I build a complementary array in numpy
How can I build a complementary array in numpy

Time:03-27

I have an array of numbers corresponding to indices of another array.

index_array = np.array([2, 3, 5])

What I want to do is to create another array with the numbers 0, 1, 4, 6, 7, 8, 9. What I have thought is:

index_list = []
for i in range(10):
    if i not in index_array:
        index_list.append(i) 

This works but I don't know if there is a more efficient way to do it or even a built-in function for it.

CodePudding user response:

You can use numpy.setdiff1d to efficiently collect the unique value from a "universal array" that aren't in your index array. Passing assume_unique=True provides a small speed up. When assume_unique is True, the result will be sorted so long as the input is sorted.

import numpy as np

# "Universal set" to take complement with respect to.
universe = np.arange(10)

a = np.array([2,3,5])

complement = np.setdiff1d(universe, a, assume_unique=True)
print(complement)

Results in

[0 1 4 6 7 8 9]

CodePudding user response:

Probably the simplest solution is just to remove unwanted indices from the set:

n = 10
index_array = [2, 3, 5]
complement = np.delete(np.arange(n), index_array)

CodePudding user response:

You could also do it with a simple list comprehension:

import numpy as np
index_array = np.array([2, 3, 5])
n = 10
complement = np.array([i for i in range(10) if i not in index_array])
print(complement)

Output:

[0 1 4 6 7 8 9]
  • Related