Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

python - IndexError: too many indices. Numpy Array with 1 row and 2 columns

When I try to get just 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 still using slicing because the full code opens and reads many different files using numpy.loadtxt() all having two columns which vary from 1 to some N.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your array a = numpy.array([1,2]) only has one dimension: its shape is (2,). However, your slice a[:,0] specifies selections for two dimensions. This causes NumPy to raise the error.

To get the first element from a you only need to write a[0] (a selection for only one dimension is being made here).


Looking at your other question, if you want to ensure that the syntax a[:,0] always works, you could ensure that a always has two dimensions. When loading an array with np.loadtxt use the ndmin parameter, e.g.:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...