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])))

程序正常运行了!

猜你喜欢

转载自blog.csdn.net/skj1995/article/details/82999687