IndexError:太多的指数。 numpy的阵列具有1行2列 [英] IndexError: too many indices. Numpy Array with 1 row and 2 columns

查看:1500
本文介绍了IndexError:太多的指数。 numpy的阵列具有1行2列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图让就这样一个数组的第一个元素

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

import numpy

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

a[:,0]

我得到这个错误

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

IndexError: too many indices

我想找到一个方法来做到这一点,而由于全code打开并使用 numpy.loadtxt()所有读取许多不同的文件仍然使用切片有两列从1变化到一定N.

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.

推荐答案

您阵 A = numpy.array([1,2])仅有的的尺寸:其形状为(2)。然而,你的片 A [:0] 指定的两个的尺寸选择。这将导致numpy的提高错误。

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.

要获得的第一个元素你只需要编写 A [0] (一个只选择一维正在这里制造)。

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

看着你等问题的,如果你想确保该语法 A [:0] 始终有效,可以确保 A 总是有两个方面。当加载与 np.loadtxt 数组使用 ndmin 参数,例如:

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)

这篇关于IndexError:太多的指数。 numpy的阵列具有1行2列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆