3

I try to get indices of an array using np.where and wish to concatenate the lists in such a manner that it gives me a 1D list. Is it possible?

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
y= np.where(l==10)
p=np.where(l==5)

If I print y and p, they give me

(array([ 0,  3,  6, 10, 14]),)

(array([ 5, 11, 13]),)

Upon appending it results in a list of tuples. However the output I want is this:

[0,3,6,10,14,5,11,13]
1
  • 1
    where produces a tuple of arrays, one per dimension. Commented Apr 17, 2018 at 16:24

6 Answers 6

9

Since there are many other solutions, I'll show you another way.

You can use np.isin to test for good values in your array:

goodvalues = {5, 10}
np.where(np.isin(l, goodvalues))[0].tolist() #  [0, 3, 6, 10, 14, 5, 11, 13]
Sign up to request clarification or add additional context in comments.

Comments

3

You could concatinate both arrays and then convert the result to a list:

result = np.concatenate((y[0], p[0])).tolist()

2 Comments

it converts the values to float. How do I keep them int?
@SunAns why you do think so? Just try type(np.concatenate((y[0], p[0])).tolist()[0]) and you'll see it's an int.
1

You can access the lists with y[0] and p[0], then append the results. Just add the line:

r = np.append(y[0], p[0])

and r will be a np.array with the values you asked. Use list(r) if you want it as a list.

Comments

1

A way to do this with concatenate:

import numpy as np

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])
y = np.where(l==10)[0]
p = np.where(l==5)[0]
k = np.concatenate((y, p))

print(k) # [ 0  3  6 10 14  5 11 13]

Comments

1

An other addition to the existing ones in one line.

l = np.array([10,20,14,10,23,5,10,1,2,3,10,5,6,5,10])

y = np.where((l == 10) | (l == 5))[0]

Numpy works with operators such as & (and), | (or), and ~ (not). The where function returns a tuple in case you pass a boolean array and hence the index 0.

Hope this helps.

Comments

0

Try this

y = [items for items in y[0]]
p = [items for items in p[0]]

then

new_list = y + p

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.