I have an array X
and a list A1
. I want to create a new list B1
such that it consists of values from X
corresponding to indices in A1
. For example, the code should pick values from X[0]
for indices in A1[0]
and so on…I present the current and expected outputs.
JavaScript
x
14
14
1
import numpy as np
2
3
X= np.array([[417.551036, 0.0, 0.0, 353.856161, 0.0, 282.754301, 0.0, 0.0,
4
134.119055, 63.4573886, 208.344718, 1e-24],
5
[417.551036, 0.0, 332.821605, 294.983702, 0.0, 278.809292,
6
126.991664, 0.0, 136.02651, 83.1512525, 207.329562, 1e-24]])
7
8
A1=[[[3, 4, 6]], [[1, 3, 6]]]
9
10
for i in range(0,len(A1)):
11
for j in range(0,len(X)):
12
B1 = [[X[j][i] for i in indices] for indices in A1[i]]
13
print(B1)
14
The current output is
JavaScript
1
3
1
[[294.983702, 0.0, 126.991664]]
2
[[0.0, 294.983702, 126.991664]]
3
The expected output is
JavaScript
1
3
1
[[353.856161, 0.0, 0.0]]
2
[[0.0, 294.983702, 126.991664]]
3
Advertisement
Answer
For the i
th element of A1
, you want to pick elements from the i
th row of X
, so iterate over A1
and X
simultaneously using zip
. In the loop, ai
is a list containing a single list. This inner list contains the indices you want.
JavaScript
1
5
1
result = []
2
for xi, ai in zip(X, A1):
3
indices = ai[0]
4
result.append(xi[indices].tolist())
5
Which gives the desired result
:
JavaScript
1
3
1
[[353.856161, 0.0, 0.0],
2
[0.0, 294.983702, 126.991664]]
3
Note that I converted xi[indices]
to a list, but if the result you want is a numpy array then you don’t need to do that, and instead just:
JavaScript
1
2
1
result = np.array([xi[ai[0]] for xi, ai in zip(X, A1)])
2
which gives a 2x3
result
array:
JavaScript
1
3
1
array([[353.856161, 0. , 0. ],
2
[ 0. , 294.983702, 126.991664]])
3