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)
5
  • 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]. Commented Mar 14, 2019 at 18:00
  • Or if you array is sorted like the one you show, use np.searchsorted(c, 5) Commented Mar 14, 2019 at 18:01
  • Try print(dir(d)) this will tell you what attributes are available Commented Mar 14, 2019 at 18:01
  • np.argmax(a==5) will give you the index of the first 5 in the array. Commented Mar 14, 2019 at 18:02
  • 1
    @wwii but won't complain if there is no 5 in a. Commented Mar 14, 2019 at 18:04

4 Answers 4

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?

Sign up to request clarification or add additional context in comments.

Comments

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)

4 Comments

I don't know why but I sure like that zip(*3*(iter(a),)) thing.
@wwii Not my invention. It is one of the itertools recipes. Search for "grouper".
Yep, I knew that - I still like it.
@wwii Yeah it's a nice little puzzle to wrap ones head around isn't it?
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])

Comments

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?

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.