Pranav Waila
Pranav Waila

Reputation: 385

Inconsistant behavior of ndarray in case of blank in python 3.X

When i am predicting a class using scikit-learn classifier model

class=modelftr.predict(X_t)

the class variable returns

>>class

array(['class1'],dtype='<U47')

whereas when I have defined a variable as

x=np.ndarray([],dtype='<U47')

calling x[0] returns

Traceback (most recent call last):

File "", line 1, in

IndexError: too many indices for array

When i am defining a variable as:

class=np.ndarray([''],dtype='<U47')

error generates as:

Traceback (most recent call last):

File "", line 1, in

TypeError: an integer is required

Why such behavior?

Upvotes: 0

Views: 95

Answers (1)

hpaulj
hpaulj

Reputation: 231510

The first example is a 1 element array:

In [50]: a=np.array(['one'],dtype='U10')

In [51]: a.shape
Out[51]: (1,)

In [52]: a[0]
Out[52]: 'one'

The second is an array with 0 elements.

In [53]: a=np.array([],dtype='U10')

In [54]: a.shape
Out[54]: (0,)

The only indexing allowed is with an empty tuple:

In [56]: a[()]
Out[56]: 
array([], 
      dtype='<U10')

On a new numpy, a[0] produces IndexError: index 0 is out of bounds for axis 0 with size 0

As for the last, creation and simple indexing works just as with the first.

In [58]: a=np.array([''],dtype='U10')

In [59]: a
Out[59]: 
array([''], 
      dtype='<U10')

In [60]: a[0]
Out[60]: ''

what code, exactly, is producing that last error?

Upvotes: 2

Related Questions