'Insert Nan into specific positions in a vector
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!
Solution 1:[1]
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]
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 |
