0

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)
user6210457
  • 397
  • 1
  • 7
  • 22
  • 1
    `where` gives you a tuple of arrays, one array per dimension. Applied to a 1d array, it is a 1 element tuple; applied to the 2d array it is a 2 element tuple. `d[0]` pulls that array out of the tuple. By the way, `d` can be used as an index, e.g. `a[d]` works just as well as `a[4]`. – hpaulj Mar 14 '19 at 18:00
  • Or if you array is sorted like the one you show, use `np.searchsorted(c, 5)` – Tarifazo Mar 14 '19 at 18:01
  • Try `print(dir(d))` this will tell you what attributes are available – Reedinationer Mar 14 '19 at 18:01
  • `np.argmax(a==5)` will give you the index of the **first** `5` in the array. – wwii Mar 14 '19 at 18:02
  • 1
    @wwii but won't complain if there is no `5` in a. – Paul Panzer Mar 14 '19 at 18:04

4 Answers4

2

...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?

wwii
  • 23,232
  • 7
  • 37
  • 77
2

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)
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
1

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?

MadLordDev
  • 260
  • 2
  • 12
1
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])
Kingsmanvk
  • 39
  • 6