将文本文件转换为列向量

2024-05-19 10:09:45 发布

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

我有一个文本文件,我想分为列向量:

dtstamp ozone   ozone_8hr_avg   

06/18/2015 14:00:00 0.071   0.059   

06/18/2015 13:00:00 0.071   0.053   

如何生成以下格式的输出?你知道吗

dtstamp = [06/18/2015 14:00:00, 06/18/2015]

ozone = [0.071, 0.071]

etc.

Tags: 格式etc向量avg文本文件ozonedtstamp
3条回答

其他答案似乎很少给出运行它们的错误。你知道吗

试试这个,它会很有魅力的!你知道吗

dtstmp = []
ozone = []
ozone_8hr_avg = []
with open('file.txt', 'r') as file:
  next(file)
  for line in file:
    if (line=="\n")  or (not line):     #If a blank line occurs
      continue
    words = line.split()                #Extract the words
    dtstmp.append(' '.join(words[0::1]))#join the date
    ozone.append(words[2])              #Add ozone
    ozone_8hr_avg.append(words[3])  #Add the third entry

print "dtstmp =", dtstmp
print "ozone =", ozone
print "ozone_8hr_avg =", ozone_8hr_avg
import datetime

dtstamp = [] # initialize the dtstamp list
ozone = [] # initialize the ozone list

with open('file.txt', 'r') as f:
    next(f) # skip the title line
    for line in f: # iterate through the file
        if not line: continue # skip blank lines
        day, time, value, _ = line.split() # split up the line
        dtstamp.append(datetime.datetime.strptime(' '.join((date, time)),
          '%m/%d/%Y %H:%M:%S') # add a date
        ozone.append(float(value)) # add a value

然后可以将这些listzip组合使用,以使用相应的日期/值:

for date, value in zip(dtstamp, ozone):
    print(date, value) # just an example

我会查看pandashttp://pandas.pydata.org或csv模块。对于cvs,您必须自己创建列,因为它将为您提供行。你知道吗

rows = [row for row in csv.reader(file,  delimiter='\t') ] #get the rows
col0 = [ row[0] for row in rows ] # construct a colonm from element 0 of each row.

相关问题 更多 >

    热门问题