'Deleting some elements and flattening the array in Python

I have an array, R. I would like to remove elements corresponding to indices in Remove and then flatten with the remaining elements. The desired output is attached.

R=np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
       [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
       [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1),(0,2)] 

R1 = R.flatten()
print([R1])

The desired output is

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])


Solution 1:[1]

You can do this with list comprehension:

import numpy as np
R=np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
       [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
       [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1),(0,2)] 
b = [[j for i, j in enumerate(m) if (k, i) not in Remove] for k, m in enumerate(R)]
R1 = np.array([i for j in b for i in j]) #Flatten the resulting list

print(R1)

Output

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])

Solution 2:[2]

One option is to use numpy.ravel_multi_index to get the index of Remove in the flattened array, then delete them using numpy.delete:

out = np.delete(R, np.ravel_multi_index(tuple(zip(*Remove)), R.shape))

Another could be to replace the values in Remove, then flatten R and filter these elements out:

R[tuple(zip(*Remove))] = R.max() + 1
arr = R.ravel()
out = arr[arr<R.max()]

Output:

array([1.05567452e+11, 6.94076420e+09, 1.96129124e+10, 1.11642674e+09,
       1.88618492e+10, 1.73640817e+10, 4.84980874e+09])

Solution 3:[3]

R = np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
              [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
              [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

R1 = np.delete(R, (1, 2))

print([R1])

Solution 4:[4]

import numpy as np

R = np.array([[1.05567452e+11, 1.51583103e+11, 5.66466172e+08],
              [6.94076420e+09, 1.96129124e+10, 1.11642674e+09],
              [1.88618492e+10, 1.73640817e+10, 4.84980874e+09]])

Remove = [(0, 1), (0, 2)]
Remove = [R.shape[1]*i+j for (i, j) in Remove]
print(np.delete(R, Remove))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nin17
Solution 2
Solution 3 Ze'ev Ben-Tsvi
Solution 4 Baigker