索引错误:索引过多.1 行 2 列的 Numpy 数组 [英] IndexError: too many indices. Numpy Array with 1 row and 2 columns

查看:28
本文介绍了索引错误:索引过多.1 行 2 列的 Numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试像这样只获取数组的第一个元素时

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

我想找到一种方法来做到这一点,同时仍然使用切片,因为完整的代码使用 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 中获取第一个元素,您只需编写 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)

这篇关于索引错误:索引过多.1 行 2 列的 Numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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