Reputation: 409
in my program I want to have 1D array, convert it to a 2D array, convert it back to a 1D array again and I want to search for a value in the final array. In order to change 1D array to 2D, I used numpy. I used where() function in order to search through the array and in the end I get this output:
(array([4], dtype=int32),)
I get this result but I only need its index, 4 in case. Is there a way which I can only get the numerical result of the where() function or is there an alternative way which allows me to do 1D to 2D and 2D to 1D conversions without using numpy?
import numpy as np
a = [1,2,3,4,5,6,7,8,9];
print(a)
b = np.reshape(a,(3,3))
print(b)
c = b.ravel()
print(c)
d = np.where(c==5)
print(d)
Upvotes: 0
Views: 1089
Reputation: 53029
No numpy version:
from itertools import chain
a = list(range(1, 10))
b = list(zip(*3*(iter(a),)))
c = list(chain.from_iterable(b))
d = c.index(5)
Upvotes: 2
Reputation: 23753
...is there an alternative way which allows me to do 1D to 2D and 2D to 1D conversions without using numpy?
:
1-d to 2-d
b = [1,2,3,4,5,6,7,8,9]
ncols = 3
new = []
for i,n in enumerate(b):
if i % ncols == 0:
z = []
new.append(z)
z.append(n)
2-d to 1-d: How to make a flat list out of list of lists?
Upvotes: 2
Reputation: 39
import numpy as np
a = [1,2,3,4,5,6,7,8,9];
print(a)
b = np.reshape(a,(3,3))
print(b)
c = b.ravel()
print(c)
d = np.where(c==5)
print(d[0][0])
Upvotes: 1
Reputation: 260
In your case
print(d[0][0])
will give you the index as integer. But if you want to use any other methods I recommend checking Is there a NumPy function to return the first index of something in an array?
Upvotes: 1