Find missing elements and insert value in place in Python

Question:

I want to find the missing elements in I[:,1] and insert 0 for these elements. For instance, the missing elements in I[:,1] are 3,6. I want to insert 0 corresponding to these elements as shown in the expected output.

import numpy as np
I=np.array([[ 0.24414794669159817        ,  1.                         ],
       [ 0.2795127725932865         ,  2.                         ],
       [ 0.2630129055948728         ,  4.                         ],
       [ 0.2518744176621288         ,  5.                         ],
       [ 0.0000000000000051625370645,  7.                         ]])

The expected output is:

array([[ 0.24414794669159817        ,  1.                         ],
       [ 0.2795127725932865         ,  2.                         ],
       [ 0.0                        ,  3.                         ]
       [ 0.2630129055948728         ,  4.                         ],
       [ 0.2518744176621288         ,  5.                         ],
       [ 0.0                        ,  6.                         ]
       [ 0.0000000000000051625370645,  7.                         ]])
Asked By: user19657580

||

Answers:

Try this out
Using numpy

 mx = int(np.max(I[:, 1])) # find max length to construct new array
 I2 = np.stack([np.zeros(mx), np.arange(1, mx + 1)], axis=1) # new array
 indices = I[:,1].astype(int) # take column as index
 I2[indices-1] = I # assign prev values to new array

Using For loop:

I1 = np.copy(I)
prev = 1
for i in I[:, 1]:
  if abs(prev - i) >= 1:
    I1 = np.insert(I1, int(i), [[0.0, float(i - 1)]], axis=0)
  
  prev = i
print(I1)

Answered By: TaQ

You do not need the loop if you use np.isin:

# Create new matrix with zeros in first column.
idx_min = min(I[:,1])
idx_max = max(I[:,1])
idxs = np.arange(idx_min, idx_max+1)
vals = np.zeros_like(idxs)
I_new = np.stack([vals, idxs], axis=1)

# replace zeros with existing data
idx_data = np.isin(I_new[:,1], I[:,1])
I_new[idx_data, 0] = I[:,0]
Answered By: Durtal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.