'convert np.where array to list
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]
Solution 1:[1]
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:
goovalues = {5, 10}
np.where(np.isin(l, goodvalues))[0].tolist() # [0, 3, 6, 10, 14, 5, 11, 13]
Solution 2:[2]
You could concatinate both arrays and then convert the result to a list:
result = np.concatenate((y[0], p[0])).tolist()
Solution 3:[3]
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.
Solution 4:[4]
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]
Solution 5:[5]
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.
Solution 6:[6]
Try this
y = [items for items in y[0]]
p = [items for items in p[0]]
then
new_list = y + p
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 | |
| Solution 2 | Mureinik |
| Solution 3 | Gianluca Micchi |
| Solution 4 | marco romelli |
| Solution 5 | Hamman Samuel |
| Solution 6 | sharmajee499 |
