Numpy日期时间窗体

2024-10-03 21:27:54 发布

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

第一次post-我正在跟随中的Python数据分析简介课程林达网. 视频中的讲师正在使用Jupiter笔记本,我正在使用Visual Studio代码进行后续操作,但我遇到了以下问题:

import numpy as np
import matplotlib.pyplot as pp
import seaborn
import urllib

def findstation(s):
    found = {code: name for code, name in stations.items() if s in name}
    print(found)

def parsefile(filename):
    return np.genfromtxt(filename,
                            delimiter = dly_delimiter,
                            usecols = dly_usecols,
                            dtype = dly_dtype,
                            names = dly_names)

dly_delimiter = [11,4,2,4] + [5,1,1,1] * 31
dly_usecols = [1,2,3] + [4*i for i in range(1, 32)]
dly_dtype = [np.int32, np.int32, (np.str_, 4)] + [np.int32]*31
dly_names = ['year', 'month', 'obs'] + [str(day) for day in range(1,31+1)]

def unroll(record):
    startdate = np.datetime64('{}-{:02}'.format(record['year'],record['month']))
    dates = np.arange(startdate, startdate + np.timedelta64(1, 'M'), np.timedelta64(1, 'D'))
    rows = [(date, record[str(i+1)]) for i,date in enumerate(dates)]
    return rows

#urllib.request.urlretrieve('ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt', 'stations.txt')
lines = open('stations.txt','r').readlines()[:10]
#print(lines)

stations = {}

for line in open('stations.txt','r'):
    if "GSN" in line:
        fields = line.split()
        stations[fields[0]] = ' '.join(fields[4:])

print(len(stations))
#findstation('LIHUE')
#findstation('SAN DIEGO')
#findstation('MINNEAPOLIS')
#findstation('IRKUTSK')

datastations = ['USW00022536', 'USW00023188', 'USW00014922', 'RSM00030710']

daily = open('USW00022536.dly', 'r').readlines()[:10]
#print(daily)
lihue = parsefile('USW00022536.dly')
u_lihue = unroll(lihue)
print(u_lihue)

将显示以下错误消息:

^{pr2}$

代码是用Jupiter笔记本电脑写的-想法?在


Tags: nameinimporttxtfordefnprecord
1条回答
网友
1楼 · 发布于 2024-10-03 21:27:54

有了这个record字典,表达式可以工作:

In [225]: record = {'year': '2119', 'month': 12}
In [226]: '{}-{:02}'.format(record['year'],record['month'])
Out[226]: '2119-12'
In [227]: np.datetime64('{}-{:02}'.format(record['year'],record['month']))
Out[227]: numpy.datetime64('2119-12')

format表达式的目的是创建一个np.datetime64可以解析的字符串。它对格式相当挑剔。在

在问题案例中可以看到record对象。在

相关问题 更多 >