1. 程式人生 > >ValueError: could not convert string to float錯誤的解決辦法

ValueError: could not convert string to float錯誤的解決辦法

錯誤:

ValueError: could not convert string to float

出錯的地方為:

month_diff = int(float(date_consumed[-6:-4])) - int(float(date_received[-6:-4])),這一句包含在函式get_time_diff中

我的目的是提取兩個時間字串裡面的月份,然後計算月份差

出錯的原因:

date_consumed或者date_received中含有空的字串,

改正方式:

我在這裡本意是將date_consumed和date_received中空的字串去除,但是後來將這兩個打印出來發現它們為空時用'nan'來表示了

frame = pd.Series(list(map(lambda x, y, z: 1. if x != 'null' and y != 'null' and z != 'null'and get_time_diff(z, y) <= 15 else 0., df[coupon_label], df[date_consumed_label], df[date_received_label])))

最終我將上面這句改成下面這句:

frame = pd.Series(list(map(lambda x, y, z: 1. if x != 'nan' and y != 'nan' and z != 'nan'and get_time_diff(z, y) <= 15 else 0., df[coupon_label], df[date_consumed_label], df[date_received_label])))

程式正常運行了!