-3

When I run this code it returns that the numpy.ndarray object has no attributes. I'm trying to write a function that in case the number given is in the array will return with the position of that number in the array.

a = np.c_[np.array([1, 2, 3, 4, 5])]
x = int(input('Type a number'))

def findelement(x, a):
    if x in a:
        print (a.index(x))    
    else:
        print (-1)

print(findelement(x, a))
Michael H.
  • 3,323
  • 2
  • 23
  • 31
cptscottz
  • 13
  • 1
  • 3
  • 1
    Well, yeah. NumPy arrays don't have an `index` method. Why are you trying to use list code with arrays? – user2357112 May 12 '19 at 19:29
  • That's because a NumPy array doesn't have a method called `index`. Maybe you were thinking of a plain Python list? – mkrieger1 May 12 '19 at 19:29
  • 1
    Possible duplicate of [Is there a NumPy function to return the first index of something in an array?](https://stackoverflow.com/questions/432112/is-there-a-numpy-function-to-return-the-first-index-of-something-in-an-array) – mkrieger1 May 12 '19 at 19:30
  • Numpy arrays don't have a `.index` attribute. Perhaps you were thinking of pandas dataframes? To find a list of attributes of an object, you can always try `dir(object)` to see these attributes. For example, try `dir(np.array([1,2,3]))` to see a list of available attributes. – Monty May 12 '19 at 20:36

2 Answers2

1

Please use np.where instead of list.index.

import numpy as np

a = np.c_[np.array([1, 2, 3, 4, 5])]

x = int(input('Type a number: '))

def findelement(x, a):
    if x in a:
        print(np.where(a == x)[0][0])    
    else:
        print(-1)

print(findelement(x, a))

Result:

Type a number: 3
2
None

Note np.where returns the indices of elements in an input array where the given condition is satisfied.

Mayur Satav
  • 985
  • 2
  • 12
  • 32
yaho cho
  • 1,779
  • 1
  • 7
  • 19
0

You should check out np.where and np.argwhere.

Michael H.
  • 3,323
  • 2
  • 23
  • 31