使用从.dat提取列np.loadtxt文件Python

2024-05-20 12:27:57 发布

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

我有这个文本文件:www2。地理ucl.ac.uk/~plewis/geog122/python/德尔诺特.dat在

我要提取第3列和第4列。在

我正在使用np.loadtxt文件-获取错误:

ValueError: invalid literal for float(): 2000-01-01

我只对2005年感兴趣。如何提取这两个列?在


Tags: 文件错误np地理acdatucl文本文件
3条回答

我同意使用csv模块。我修改了这个答案:reading csv files in scipy/numpy in Python 适用于你的问题。不确定您是否需要numpy数组中的数据,或者列表是否足够。在

import numpy as np
import urllib2
import csv

txtFile = csv.reader(open("delnorte.dat.txt", "r"), delimiter='\t')

fields = 5                   
records = [] 
for row, record in enumerate(txtFile):
    if (len(record) != fields or record[0]=='#'):
        pass
        # print "Skipping malformed record or comment: {}, contains {} fields ({} expected)".format(record,len(record),fields)
    else:
        if record[2][0:4] == '2005': 
            # assuming you want columns 3 & 4 with the first column indexed as 0
            records.append([int(record[:][3]), record[:][4]] ) 

# if desired slice the list of lists to put a single column into a numpy array
npData = np.asarray([ npD[0] for npD in records] ) 

您可以为特定列提供自定义的转换函数到loadtxt
由于您只对年份感兴趣,我使用lambda-函数来分割-上的日期,并将第一部分转换为int

data = np.loadtxt('delnorte.dat',
         usecols=(2,3),
         converters={2: lambda s: int(s.split('-')[0])},
         skiprows=27)

array([[ 2000.,   190.],
       [ 2000.,   170.],
       [ 2000.,   160.],
       ..., 
       [ 2010.,   185.],
       [ 2010.,   175.],
       [ 2010.,   165.]])

要过滤年度2005,可以在numpy中使用logical indexing

^{pr2}$

你不应该使用NumPy.loadtxt文件要读取这些值,您应该使用^{} module来加载文件并读取其数据。在

相关问题 更多 >