[英]Issues Reading Dates from .txt File Python
我目前有一個腳本,用於在將 csv 文件轉換為 .txt 后繪制它的一部分。 此時,它運行良好,除了當我將第 0 列中的日期更改為序數形式(我這樣做是為了將所有值讀取為浮點數並在第 4 列上執行計算)時,Python 將小時、分鍾和秒。 我仍然需要小時和分鍾,因為當我繪制數據時,它會在一天開始時繪制我的所有點。 有沒有辦法可以做到這一點並保持時間和日期? 我嘗試將日期轉換為字符串,將另一列轉換為浮點數,但它變得非常混亂和混亂。 這是我的代碼:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import csv
from numpy import ma
def skip_first(seq,n):
for i, item in enumerate(seq):
if i >= n:
yield item
g = open('soundTransit1_remote_rawMeasurements_15m.txt', 'w')
with open('soundTransit1_remote_rawMeasurements_15m.dat', 'rb') as f:
csvreader = csv.reader(f)
for row in skip_first(csvreader,4):
for row in csv.reader(f,delimiter=',',skipinitialspace=True):
print >>g, "\t".join(row)
g.close()
def date2str(date_str):
date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
return date.toordinal()
def readfiles(file_list):
""" read <TAB> delemited files as strings
ignoring '# Comment' lines """
data = []
for fname in file_list:
data.append(
np.loadtxt(fname,
usecols=(0,4),
comments='#', # skip comment lines
delimiter='\t',
converters = { 0 : date2str },
dtype=None))
return data
data = readfiles(['soundTransit1_remote_rawMeasurements_15m.txt'])
data_1 = ma.fix_invalid(data, fill_value = 'nan')
column_0 = np.array(data_1)[0][:,0]
airTempRaw = np.array(data_1)[0][:,1]
#Compute Air Temperature
airTempRs_ohms = 23100*(airTempRaw/(1-airTempRaw))
airTemp_degC = -39.17*np.log(airTempRs_ohms) + 410.43
def init_plot(title, yMin=-10, yMax=40):
plt.figure(figsize=(24, 12))
plt.title(title + disclamers)
plt.xlabel(xtext)
plt.ylabel(ytext)
#plt.xlim(xMin,xMax)
plt.ylim(yMin,yMax)
plt.grid()
#plt.xticks(np.arange(xMin,xMax+1))
def end_plot(name=None, cols=5):
plt.legend(bbox_to_anchor=(0, -.1, 1, -0.5), loc=8, ncol=cols,
mode="expand", borderaxespad=-1., scatterpoints=1)
if name:
plt.savefig(name, bbox_inches='tight')
disclamers = ('\nUSGS PROVISIONAL DATA'
'\nSUBJECT TO REVISION'
)
xtext = ('Date & Time')
ytext = ('Air Temperature, deg C')
init_plot('Air Temperature')
plt.plot(column_0, airTemp_degC, linestyle='-', color='b', label='Air Temperature')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d\n%H:%M'))
plt.gca().xaxis.set_minor_locator(mdates.HourLocator(interval=6))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1))
end_plot(name='py_airTemp.png')
在此先感謝您的幫助!
您沒有說日期列的格式是什么,但我認為問題在於您的轉換器np.loadtxt()
。
從 matplotlib 檢查這個例子: http ://matplotlib.org/examples/pylab_examples/load_converter.html?highlight= strpdate2num
我相信這應該有效:
from matplotlib.dates import strpdate2num
def readfiles(file_list):
""" read <TAB> delemited files as strings
ignoring '# Comment' lines """
data = []
for fname in file_list:
data.append(
np.loadtxt(fname,
usecols=(0,4),
comments='#', # skip comment lines
delimiter='\t',
converters = { 0 : strpdate2num('%Y-%m-%d %H:%M:%S') },
dtype=None))
return data
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.