1
這種結構荷載與熊貓一個數據幀(從CSV)後生成2個日期時間列,比如'startdate'和'enddate'。由於缺少需要處理的值,因此read_csv中的parse_dates & date_parser參數看起來有點笨拙,所以我編寫了下面的函數。建設日期時間
首先,我填寫NaN值,以便將月份和日期從浮點數轉換爲整數,然後將它們串在一起進行解析。
def dateparser(y=df.startyear,m=df.startmonth,d=df.startday):
m = m.fillna(1).astype(int)
d = d.fillna(1).astype(int)
x = str(y) + " " + str(m) + " " + str(d)
return pd.datetime.strptime(x, '%Y %m %d')
所得錯誤消息是有點混亂,因爲字符串格式應該是什麼strptime預期完全一致。
n [338]: dateparser()
Traceback (most recent call last):
File "<ipython-input-338-917257f547ca>", line 1, in <module>
dateparser()
File "<ipython-input-337-41aa89124ae6>", line 5, in dateparser
return pd.datetime.strptime(x, '%Y %m %d')
File "/Users/Username/anaconda/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/Users/Username/anaconda/lib/python3.5/_strptime.py", line 343, in _strptime
(data_string, format))
ValueError: time data 'caseid\n1945121601 1945\n1946031101
1946\n1946110101 1946\n1947022401 1947\n1947053101
1947\n1947111001 1947\n1947120501 1947\n1947120502
1947\n1947120503 1947\n1947120504 1947\n1947120505
1947\n1947120506 1947\n1947120507 1947\n1947122001
1947\n1948032501 1948\n1948032502 1948\n1948070101
6\n2005100601 10\n
Name: startmonth, dtype: int64 caseid\n1945121601 16\n1946031101
6\nName: startday, dtype: int64' does not match format '%Y %m %d'`
我也試過其他分析軟件包,打開大部分的時間字符串在英語爲日期時間變量的沒有問題:
from dateutil.parser import parse
def dateparser():
(same function as above)
return parse(x)
而且這也導致錯誤(ValueError異常:未知字符串格式)。 ..
任何想法如何改善功能非常感謝。對我而言,大多數包函數只是將字符串轉換爲日期時間,並且需要將整數/浮點數轉換爲字符串,即使它不應該很難直接將數字數據轉換爲日期時間格式也是有點奇怪的。錯過一些明顯的解
放了'''試着在違規線/ except'''塊,趕上'''ValueError''',在'''except'''套件打印出來的函數參數和您的日期字符串 - '''x'''。這應該讓你知道發生了什麼。如果你希望它在那個點停止,請重新提出'''except''套件中的錯誤.https://docs.python.org/3/tutorial/errors.html#handling-exceptions – wwii
非常感謝如何調試這個提示!我已成功找到問題並將在下面回答以供參考。 –