Python 2.7 如何从python中的文本文件加载位置不同的特定列?

Python 2.7 如何从python中的文本文件加载位置不同的特定列?,python-2.7,numpy,text-files,Python 2.7,Numpy,Text Files,我正在试图读取在线存储在文本文件中的346条美国河流的流量数据。文件大致采用以下格式: Measurement_number Date Gage_height Discharge_value 1 2017-01-01 10 1000 2 2017-01-20 15 2000 # etc. 我只想阅读计量器高度和

我正在试图读取在线存储在文本文件中的346条美国河流的流量数据。文件大致采用以下格式:

Measurement_number    Date          Gage_height     Discharge_value     
1                     2017-01-01    10              1000
2                     2017-01-20    15              2000
# etc.
我只想阅读计量器高度和流量值列。 问题是,在大多数文件中,在“规格高度”列前面添加了附加的元数据列,因此我不能简单地读取第3列和第4列,因为它们的索引不同

我试图找到一种方式来说‘读取名为‘Gage_height’和‘Discharge_value’的列,但我还没有成功

我希望任何人都能帮忙。我目前正在尝试使用numpy.genfromtxt加载文本文件,因此使用该软件包找到一个解决方案会很好,但其他解决方案也非常受欢迎

这是到目前为止我的代码

data_url=urllib2.urlopen(#the url of this specific site)
data=np.genfromtxt(data_url,skip_header=1,comments='#',usecols=2,3])

您可以使用
names=True
选项选择
genfromtxt
,然后使用列名选择要使用
usecols
读取的列

例如,要从数据文件中读取
“量规高度”
“排放值”

data = np.genfromtxt(filename, names=True, usecols=['Gage_height', 'Discharge_value'])
请注意,如果使用
names=True
,则不需要设置
skip_header=1

然后可以使用列的名称访问这些列:

gage_height = data['Gage_height']               #  == array([ 10.,  15.])
discharge_value = data['Discharge_value']       #  == array([ 1000.,  2000.])

有关更多信息,请参阅。

您的标题行似乎非常可分离。只需读取第一行(
fid=open(path,“r”);first=fid.readline().split(“”);col1=first.index(“Gage_height”);col2=first.index(“Discharge_value”)
)并从中获取所需列的索引。