numpy array TypeError: only integer scalar arrays

2020-02-09 05:46发布

i=np.arange(1,4,dtype=np.int)
a=np.arange(9).reshape(3,3)

and

a
>>>array([[0, 1, 2],
          [3, 4, 5],
          [6, 7, 8]])
a[:,0:1]
>>>array([[0],
          [3],
          [6]])
a[:,0:2]
>>>array([[0, 1],
          [3, 4],
          [6, 7]])
a[:,0:3]
>>>array([[0, 1, 2],
          [3, 4, 5],
          [6, 7, 8]])

Now I want to vectorize the array to print them all together. I try

a[:,0:i]

or

a[:,0:i[:,None]]

It gives TypeError: only integer scalar arrays can be converted to a scalar index

7条回答
爷、活的狠高调
2楼-- · 2020-02-09 06:09

this problem arises when we use vectors in place of scalars for example in a for loop the range should be a scalar, in case you have given a vector in that place you get error. So to avoid the problem use the length of the vector you have used

查看更多
\"骚年 ilove
3楼-- · 2020-02-09 06:10

This could be unrelated to this specific problem, but I ran into a similar issue where I used NumPy indexing on a Python list and got the same exact error message:

# incorrect
weights = list(range(1, 129)) + list(range(128, 0, -1))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
# TypeError: only integer scalar arrays can be converted to a scalar index

It turns out I needed to turn weights, a 1D Python list, into a NumPy array before I could apply multi-dimensional NumPy indexing. The code below works:

# correct
weights = np.array(list(range(1, 129)) + list(range(128, 0, -1)))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
查看更多
再贱就再见
4楼-- · 2020-02-09 06:15

You can use numpy.ravel to return a flattened array from n-dimensional array:

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
查看更多
干净又极端
5楼-- · 2020-02-09 06:23

try the following to change your array to 1D

a.reshape((1, -1))
查看更多
迷人小祖宗
6楼-- · 2020-02-09 06:28

I had a similar problem and solved it using list...not sure if this will help or not

classes = list(unique_labels(y_true, y_pred))
查看更多
对你真心纯属浪费
7楼-- · 2020-02-09 06:28

I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.

The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument

查看更多
登录 后发表回答