Home > Enterprise >  Insert Nan into specific positions in a vector
Insert Nan into specific positions in a vector

Time:05-25

I have two vectors called A and B: A is a list of numbers and B is a list that indicates the order that the numbers of A should be arranged.

I would like to create a vector C, where the numbers of vector A are arranged according to the positions laid out in vector B.

The numbers in A don't cover the entire range of possible positions in B, so I need to create a vector C with NaN or [] for missing A values. What is the fastest way of doing this?

See example below:

A = [5, 10, 55, 3, 10]
B = [1, 3, 4, 6, 9]
C = [5, nan, 10, 55, nan, 3, nan, nan, 10]

Thanks for your help!

CodePudding user response:

ans = [nan for _ in range(B[-1])]
for i, v in enumerate(B):
    ans[v - 1] = A[i]
ans
# [5, nan, 10, 55, nan, 3, nan, nan, 10]

Using numpy

ans = numpy.array([nan for _ in range(B[-1])])
ans[numpy.array(B) - 1] = A
ans
# array([ 5., nan, 10., 55., nan,  3., nan, nan, 10.])

CodePudding user response:

short answer using numpy and avoiding "for"

import numpy as np

A = np.array([5, 10, 55, 3, 10])
B = np.array([1, 3, 4, 6, 9])
#C = [5, nan, 10, 55, nan, 3, nan, nan, 10]

c = np.ones(B[-1])*np.NaN #create array of nans with desired length
c[B-1] = A #assing values (remember indices in python starts at 0)

print(c)
#[ 5. nan 10. 55. nan  3. nan nan 10.]

CodePudding user response:

try

C = [A[B.index(i)] if i in B else nan for i in range(max(B)   1)]
# [nan, 5, nan, 10, 55, nan, 3, nan, nan, 10]

or if you really want to skip index 0:

C = [A[B.index(i)] if i in B else nan for i in range(1, max(B)   1)]
# [5, nan, 10, 55, nan, 3, nan, nan, 10]
  • Related