IndexError: Too many indexes. Numpy array with 1 row and 2 columns

When I try to get only the first element of an array like this

import numpy

a = numpy.array([1,2])

a[:,0]

I get this error

---------------------------------------------------------------------------
 IndexError                                Traceback (most recent call last)
<ipython-input-3-ed371621c46c> in <module>()
----> 1 a[:,0]

IndexError: too many indices

I would like to find a way to do this while continuing to use slicing, because the full code opens and reads many different files using numpy.loadtxt(), all of which have two columns that range from 1 to some N.

+4
source share
4 answers

There a = numpy.array([1,2])is only one dimension in your array : its shape (2,). However, your fragment a[:,0]determines the choice for two dimensions. This causes NumPy to throw an error.

a, a[0] ( ).


, , a[:,0] , , a . np.loadtxt ndmin, :

np.loadtxt(F, skiprows=0, ndmin=2)
+11

, , .

, , , , numpy 1D- 2D- ( ):

>>> a = np.array([0,1,2])
>>> a.shape
(3,)
>>> a_row = a[None,:]
>>> a_row.shape
(1,3)
>>> a_col = a[:,None]
>>> a_col.shape
(3,1)
+4

, 1-1000 . , numpy genfromtxt, "ndmin", , , - 1 1 :

>>> arr=np.genfromtxt('file',names=['a','b'],dtype='f4,f4') 
>>> if (np.size(arr) == 1): arr.shape=1

1 , :

>>> for i in range(np.size(arr)): print arr['a'][i]
+1

, ,

0

Source: https://habr.com/ru/post/1659403/


All Articles