Home > database >  Deleting some elements and flattening the array in Python
Deleting some elements and flattening the array in Python

Time:04-18

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])

CodePudding user response:

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])

CodePudding user response:

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])

CodePudding user response:

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])

CodePudding user response:

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))
  • Related