我寫了一個函數來分析this wind file (wind.txt ~1MB)成大熊貓數據幀,但它很慢,因爲文件格式的污穢(根據我的同事)。以上鍊接的文件僅僅是具有每小時風速數據較大的文件的一個子集,從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個小時測量爲一個單一的一天都在同一行上。
我在做什麼是閱讀本文件的內容與日期時間指數(每小時頻率)和兩列(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模型工作,我有各種輸入/輸出文件幾十個類似的解析器能夠分析/創建/修改它們的蟒蛇。如果我可以節省每一個時間,我想知道如何。非常感謝!
如果你的代碼已經工作,你可能會更好地在CodeReview上發佈這個代碼 - SO代碼中的問題更多。 – asongtoruin