1

我只想加载文本文件中的最后几列并进行一些评估。

我使用带有参数 converters={-1:func,-2:func} 的 numpy.genfromtxt

但它不起作用。另一方面,如果我像 converters={56:func,57:func} 这样的前向索引它可以正常工作。

为什么转换器参数不支持 python 的后向索引?如果我只知道最后一列的索引,有没有办法做到这一点?

4

1 回答 1

1

使用numpy.loadtxt它可以工作,您可以使用该converters参数来定义您的功能。有一个tmp.txt文件:

11,12,13,14,15,16,17,18,19
21,22,23,24,25,26,27,28,29
31,32,33,34,35,36,37,38,39
41,42,43,44,45,46,47,48,49
51,52,53,54,55,56,57,58,59

您可以加载选定的列(也选择您希望它们堆叠的顺序):

import numpy as np
print np.loadtxt('tmp.txt',delimiter=',',usecols=(-2,-1))
#[[ 18.  19.]
# [ 28.  29.]
# [ 38.  39.]
# [ 48.  49.]
# [ 58.  59.]]
print np.loadtxt('tmp.txt',delimiter=',',usecols=(-1,-2),converters={-1: lambda x: float(x)+100})
#[[ 119.   18.]
# [ 129.   28.]
# [ 139.   38.]
# [ 149.   48.]
# [ 159.   58.]]
于 2013-05-12T13:20:44.650 回答