1

I have two arrays A and B. I have a list indices.

I want to locate each element of indices in A and print the corresponding values from B. I present the current and expected outputs.

import numpy as np

A=np.array([[ 0,  4],
       [ 0,  5],
       [1,6]])

B=np.array([[9.16435586e-05],
       [1.84193464e-14],
       [1.781909182e-5]])

indices= [[0,4],[1,6]]

for i in range(0,len(indices)):
    A=indices[i]
    print(A)

The current output is:

[0, 4]
[1, 6]

The expected output is:

[[0,4],[1,6]]
[[9.16435586e-05],[1.781909182e-5]]
4
  • Your code never uses B. How could you expect to print its values??? Commented Feb 13, 2023 at 7:51
  • That's right. I don't really know how to refer the order so as to print values from B. Commented Feb 13, 2023 at 7:54
  • but indices= [[0,4],[1,6]] contains slices of A, not indices Commented Feb 13, 2023 at 8:01
  • You can call whatever you like. Basically, I want to locate [0,4] from indices in A and print the corresponding value from B i.e. [9.16435586e-05]. Similarly, for [1,6]. Commented Feb 13, 2023 at 8:03

4 Answers 4

1
common_index=[x for x,y in enumerate(A) if list(y) in indices]
#[0, 2]
lst=[]

for t in common_index:
    lst.append(list(B[t]))

#output
[[9.16435586e-05], [1.781909182e-05]]
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to append the B values?
1

To generate a list based on index match I would do it like that, you can also modify this based on your use case

new_list = []
for i, elem in enumerate(A):
    if list(elem) in indices:
        new_list.append(B[i])

Comments

1

Numpy is good at processing arrays of numbers in a vectorized way. Here, you would better use plain Python lists:

A = [[ 0,  4],
       [ 0,  5],
       [1,6]]
B = [[9.16435586e-05],
       [1.84193464e-14],
       [1.781909182e-5]]
indices= [[0,4],[1,6]]
print([A[i] for i,v in enumerate(A) if v in indices])
print([B[i] for i,v in enumerate(A) if v in indices])

gives as expected:

[[0, 4], [1, 6]]
[[9.16435586e-05], [1.781909182e-05]]

Comments

1

You can use numpy's where method to achieve this:

import numpy as np

A=np.array([[ 0,  4],
       [ 0,  5],
       [1,6]])

B=np.array([[9.16435586e-05],
       [1.84193464e-14],
       [1.781909182e-5]])

indices= [[0,4],[1,6]]

for i in range(0,len(indices)):
    index = np.where(A == i)
    print(index)
    print(A[index])
    print(B[index])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.