numpy loadtxt索引器错误:列表索引超出范围

2024-05-11 22:34:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,目前我有一个文本文件,如下所示:

# Wed 13:10:08 11-Mar-2015
 begin  aperture image1 1 1024. 139.7445
 image  image1
 aperture   1
 beam   1
 center 1024. 139.7445
 low        -1023. -4.
 high   1024. 4.
 background
         xmin -40.45428
         xmax 43.75221
         function chebyshev
         order 3
         sample -40.45428:-18.42313 20.09063:43.75221
         naverage 1
         niterate 0
         low_reject 3.
         high_reject 3.
         grow 0.
 axis    2
 curve   6
         2.
         2.
         4.
         2044.
         -0.1275881
         -0.03320996 

我想从第六行(中间)提取“139.7445”。这是我的代码:

pos_wasp = np.loadtxt(line, skiprows=5, usecols=(3,4), unpack=True)

但当我运行它时,它会给出一个错误:

IndexError: list index out of range

这应该是一个简单的问题来解决,我已经尝试了很多次更改列号和数据类型,但仍然没有成功。


Tags: imagemarlowbeambackgroundcenterxmin文本文件
3条回答

如果您在使用numpy.loadtxt时对IndexError: list index out of range感到沮丧后访问此页,请不要绝望。

失败的原因是输入文本文件中的一行或多行不包含在usecols=()中指定的列。

若要更正此错误,请检查文本文件中的所有行是否都具有要提取的列。

我认为您的代码是失败的,因为loadtxt希望在您的值打开后读取所有行。为了得到这一个值,为什么不直接读取文件(inpp.txt,或者您所调用的任何文件):

with open('inpp.txt') as fi:
    for line in fi:
        fields = line.split()
        if fields[0] == 'center':
            val = float(fields[2])
            break

print(val)

文本文件的末尾有新行吗?如果是的话,把它扔掉看看是否有效。

相关问题 更多 >