将固定宽度的交替行文件缓慢解析为 pandas 数据帧
Slow parsing of fixed-width, alternating-line file to pandas dataframe
我已经编写了一个函数来将 this wind file (wind.txt ~1MB) 解析为 pandas 数据帧,但是由于文件格式的肮脏,它非常慢(根据我的同事的说法)。上面链接的文件只是较大文件的一个子集,该文件具有从 1900 年到 2016 年的每小时风数据。这是文件的一个片段:
2000 1 1 CCB Wdir 5 11 15 14 14 14 14 16 15 15 15 15 13 12 16 16 15 15 15 15 15 14 14 14
2000 1 1 CCB Wspd 10 8 6 8 7 7 8 8 6 8 9 7 16 16 7 10 12 14 15 17 18 22 22 20
2000 1 2 CCB Wdir 14 14 14 14 14 16 16 16 16 15 15 16 17 17 16 17 16 16 16 15 15 15 15 16
2000 1 2 CCB Wspd 17 16 15 17 15 15 16 14 14 15 17 16 15 13 14 15 15 21 20 20 18 25 23 21
2000 1 3 CCB Wdir 15 15 15 16 15 16 16 16 16 16 16 20 18 22 28 27 26 31 32 32 33 33 35 33
2000 1 3 CCB Wspd 20 22 22 18 20 21 21 22 18 16 14 13 15 6 3 7 8 8 13 13 15 10 6 7
列是年、月、日、站点名称、变量名称、小时00、小时01、小时02、...、小时23。风向和风速度显示在每一天的交替线上,一天的 24 小时测量值都在同一条线上。
我正在做的是将此文件的内容读入单个 pandas 数据帧,该数据帧具有日期时间索引(每小时频率)和两列(wdir 和 wspd)。我的解析器如下:
import pandas as pd
from datetime import timedelta
fil = 'D:\wind.txt'
lines = open(fil, 'r').readlines()
nl = len(lines)
wdir = lines[0:nl:2]
wspd = lines[1:nl:2]
first = wdir[0].split()
start = pd.datetime(int(first[0]), int(first[1]), int(first[2]), 0)
last = wdir[-1].split()
end = pd.datetime(int(last[0]), int(last[1]), int(last[2]), 23)
drange = pd.date_range(start, end, freq='H')
wind = pd.DataFrame(pd.np.nan, index=drange, columns=['wdir','wspd'])
idate = start
for d in range(nl/2):
dirStr = wdir[d].split()
spdStr = wspd[d].split()
for h in range(24):
if dirStr[h+5] != '-9' and spdStr[h+5] != '-9':
wind.wdir[idate] = int(dirStr[h+5]) * 10
wind.wspd[idate] = int(spdStr[h+5])
idate += timedelta(hours=1)
if idate.month == 1 and idate.day == 1 and idate.hour == 1:
print idate
现在解析一年大约需要2.5秒,我认为这已经很不错了,但是我的同事认为应该可以在几秒内解析完整的数据文件。他是对的吗?我是否在浪费宝贵的时间来编写缓慢、笨重的解析器?
我在一个庞大的遗留 FORTRAN77 模型上工作,我有几十个类似的解析器用于各种 input/output 文件,以便能够 analyze/create/modify 它们在 python 中。如果我能在他们每个人身上节省时间,我想知道怎么做。非常感谢!
我会使用 pd.read_fwf(...) or pd.read_csv(..., delim_whitespace=True) 方法 - 它旨在解析此类文件...
演示:
cols = ['year', 'month', 'day', 'site', 'var'] + ['{:02d}'.format(i) for i in range(24)]
fn = r'C:\Temp\.data763897.txt'
df = pd.read_csv(fn, names=cols, delim_whitespace=True, na_values=['-9'])
x = pd.melt(df,
id_vars=['year','month','day','site','var'],
value_vars=df.columns[5:].tolist(),
var_name='hour')
x['date'] = pd.to_datetime(x[['year','month','day','hour']], errors='coerce')
x = (x.drop(['year','month','day','hour'], 1)
.pivot_table(index=['date','site'], columns='var', values='value')
.reset_index())
结果:
In [12]: x
Out[12]:
var date site Wdir Wspd
0 2000-01-01 00:00:00 CCB 5.0 10.0
1 2000-01-01 01:00:00 CCB 11.0 8.0
2 2000-01-01 02:00:00 CCB 15.0 6.0
3 2000-01-01 03:00:00 CCB 14.0 8.0
4 2000-01-01 04:00:00 CCB 14.0 7.0
5 2000-01-01 05:00:00 CCB 14.0 7.0
6 2000-01-01 06:00:00 CCB 14.0 8.0
7 2000-01-01 07:00:00 CCB 16.0 8.0
8 2000-01-01 08:00:00 CCB 15.0 6.0
9 2000-01-01 09:00:00 CCB 15.0 8.0
... ... ... ... ...
149030 2016-12-31 14:00:00 CCB 0.0 0.0
149031 2016-12-31 15:00:00 CCB 1.0 5.0
149032 2016-12-31 16:00:00 CCB 33.0 8.0
149033 2016-12-31 17:00:00 CCB 34.0 9.0
149034 2016-12-31 18:00:00 CCB 35.0 7.0
149035 2016-12-31 19:00:00 CCB 0.0 0.0
149036 2016-12-31 20:00:00 CCB 12.0 8.0
149037 2016-12-31 21:00:00 CCB 13.0 7.0
149038 2016-12-31 22:00:00 CCB 15.0 7.0
149039 2016-12-31 23:00:00 CCB 17.0 7.0
[149040 rows x 4 columns]
与您的 wind.txt
文件的时间安排:
In [10]: %%timeit
...: cols = ['year', 'month', 'day', 'site', 'var'] + ['{:02d}'.format(i) for i in range(24)]
...: fn = r'D:\download\wind.txt'
...: df = pd.read_csv(fn, names=cols, delim_whitespace=True, na_values=['-9'])
...: x = pd.melt(df,
...: id_vars=['year','month','day','site','var'],
...: value_vars=df.columns[5:].tolist(),
...: var_name='hour')
...: x['date'] = pd.to_datetime(x[['year','month','day','hour']], errors='coerce')
...: x = (x.drop(['year','month','day','hour'], 1)
...: .pivot_table(index=['date','site'], columns='var', values='value')
...: .reset_index())
...:
1 loop, best of 3: 812 ms per loop
我已经编写了一个函数来将 this wind file (wind.txt ~1MB) 解析为 pandas 数据帧,但是由于文件格式的肮脏,它非常慢(根据我的同事的说法)。上面链接的文件只是较大文件的一个子集,该文件具有从 1900 年到 2016 年的每小时风数据。这是文件的一个片段:
2000 1 1 CCB Wdir 5 11 15 14 14 14 14 16 15 15 15 15 13 12 16 16 15 15 15 15 15 14 14 14
2000 1 1 CCB Wspd 10 8 6 8 7 7 8 8 6 8 9 7 16 16 7 10 12 14 15 17 18 22 22 20
2000 1 2 CCB Wdir 14 14 14 14 14 16 16 16 16 15 15 16 17 17 16 17 16 16 16 15 15 15 15 16
2000 1 2 CCB Wspd 17 16 15 17 15 15 16 14 14 15 17 16 15 13 14 15 15 21 20 20 18 25 23 21
2000 1 3 CCB Wdir 15 15 15 16 15 16 16 16 16 16 16 20 18 22 28 27 26 31 32 32 33 33 35 33
2000 1 3 CCB Wspd 20 22 22 18 20 21 21 22 18 16 14 13 15 6 3 7 8 8 13 13 15 10 6 7
列是年、月、日、站点名称、变量名称、小时00、小时01、小时02、...、小时23。风向和风速度显示在每一天的交替线上,一天的 24 小时测量值都在同一条线上。
我正在做的是将此文件的内容读入单个 pandas 数据帧,该数据帧具有日期时间索引(每小时频率)和两列(wdir 和 wspd)。我的解析器如下:
import pandas as pd
from datetime import timedelta
fil = 'D:\wind.txt'
lines = open(fil, 'r').readlines()
nl = len(lines)
wdir = lines[0:nl:2]
wspd = lines[1:nl:2]
first = wdir[0].split()
start = pd.datetime(int(first[0]), int(first[1]), int(first[2]), 0)
last = wdir[-1].split()
end = pd.datetime(int(last[0]), int(last[1]), int(last[2]), 23)
drange = pd.date_range(start, end, freq='H')
wind = pd.DataFrame(pd.np.nan, index=drange, columns=['wdir','wspd'])
idate = start
for d in range(nl/2):
dirStr = wdir[d].split()
spdStr = wspd[d].split()
for h in range(24):
if dirStr[h+5] != '-9' and spdStr[h+5] != '-9':
wind.wdir[idate] = int(dirStr[h+5]) * 10
wind.wspd[idate] = int(spdStr[h+5])
idate += timedelta(hours=1)
if idate.month == 1 and idate.day == 1 and idate.hour == 1:
print idate
现在解析一年大约需要2.5秒,我认为这已经很不错了,但是我的同事认为应该可以在几秒内解析完整的数据文件。他是对的吗?我是否在浪费宝贵的时间来编写缓慢、笨重的解析器?
我在一个庞大的遗留 FORTRAN77 模型上工作,我有几十个类似的解析器用于各种 input/output 文件,以便能够 analyze/create/modify 它们在 python 中。如果我能在他们每个人身上节省时间,我想知道怎么做。非常感谢!
我会使用 pd.read_fwf(...) or pd.read_csv(..., delim_whitespace=True) 方法 - 它旨在解析此类文件...
演示:
cols = ['year', 'month', 'day', 'site', 'var'] + ['{:02d}'.format(i) for i in range(24)]
fn = r'C:\Temp\.data763897.txt'
df = pd.read_csv(fn, names=cols, delim_whitespace=True, na_values=['-9'])
x = pd.melt(df,
id_vars=['year','month','day','site','var'],
value_vars=df.columns[5:].tolist(),
var_name='hour')
x['date'] = pd.to_datetime(x[['year','month','day','hour']], errors='coerce')
x = (x.drop(['year','month','day','hour'], 1)
.pivot_table(index=['date','site'], columns='var', values='value')
.reset_index())
结果:
In [12]: x
Out[12]:
var date site Wdir Wspd
0 2000-01-01 00:00:00 CCB 5.0 10.0
1 2000-01-01 01:00:00 CCB 11.0 8.0
2 2000-01-01 02:00:00 CCB 15.0 6.0
3 2000-01-01 03:00:00 CCB 14.0 8.0
4 2000-01-01 04:00:00 CCB 14.0 7.0
5 2000-01-01 05:00:00 CCB 14.0 7.0
6 2000-01-01 06:00:00 CCB 14.0 8.0
7 2000-01-01 07:00:00 CCB 16.0 8.0
8 2000-01-01 08:00:00 CCB 15.0 6.0
9 2000-01-01 09:00:00 CCB 15.0 8.0
... ... ... ... ...
149030 2016-12-31 14:00:00 CCB 0.0 0.0
149031 2016-12-31 15:00:00 CCB 1.0 5.0
149032 2016-12-31 16:00:00 CCB 33.0 8.0
149033 2016-12-31 17:00:00 CCB 34.0 9.0
149034 2016-12-31 18:00:00 CCB 35.0 7.0
149035 2016-12-31 19:00:00 CCB 0.0 0.0
149036 2016-12-31 20:00:00 CCB 12.0 8.0
149037 2016-12-31 21:00:00 CCB 13.0 7.0
149038 2016-12-31 22:00:00 CCB 15.0 7.0
149039 2016-12-31 23:00:00 CCB 17.0 7.0
[149040 rows x 4 columns]
与您的 wind.txt
文件的时间安排:
In [10]: %%timeit
...: cols = ['year', 'month', 'day', 'site', 'var'] + ['{:02d}'.format(i) for i in range(24)]
...: fn = r'D:\download\wind.txt'
...: df = pd.read_csv(fn, names=cols, delim_whitespace=True, na_values=['-9'])
...: x = pd.melt(df,
...: id_vars=['year','month','day','site','var'],
...: value_vars=df.columns[5:].tolist(),
...: var_name='hour')
...: x['date'] = pd.to_datetime(x[['year','month','day','hour']], errors='coerce')
...: x = (x.drop(['year','month','day','hour'], 1)
...: .pivot_table(index=['date','site'], columns='var', values='value')
...: .reset_index())
...:
1 loop, best of 3: 812 ms per loop