Could not convert string to float: ''

Hi to everybody,

In pandas I want to convert a string column in a float one, but I get all the time the same error message: could not convert string to float: ‘’

The content of this column is the following: 2019-08-06T16:47:07.508

So I replaced “-”, “T”, “:” and “.” with following code:

climbing[“UTC time”] = climbing[“UTC time”].replace(“-”, “”, regex=True)
climbing[“UTC time”] = climbing[“UTC time”].replace(“:”, “”, regex=True)
climbing[“UTC time”] = climbing[“UTC time”].replace(“.”, “”, regex=True)
climbing[“UTC time”] = climbing[“UTC time”].replace(“T”, “0”, regex=True)

but, all the time when I tipping the following code:
climbing[“UTC time”] = climbing[“UTC time”].astype(float)

I get: could not convert string to float: ‘’

Any ideas why?

Thanks a lot!

. matches anything in a regular expression, so this will empty your column.

Dear Chris,
Thanks a lot for your answer…now it works.

Kind regards,
Sebastian

So that you can solve problems like this for yourself more easily in the future, I want to try to talk through the debugging process.

Okay, so what exactly is the goal? For that string, what float value should we get, and why? Step by step, what logic do you want it to use?

Okay, and after those steps, what value did you see for climbing["UTC time"]? Does it make sense to try to convert that to a float? What do you think the result should be?

Okay, so that tells you pretty directly what happened: the string was completely erased. Does that agree with what you observe, for example, if you try to check the climbing["UTC time"] value directly?

What if you try checking it after each step? Can you see where something goes wrong?

(Hint: when you write regex=True, what do you expect this to mean? Assuming that you understand what regex is generally - can you see why using a regex like ".", and replacing those matches with "", might cause a problem?)

general advice would be to not use regex=True whenever you don’t need it, as it’s unnecessarily slowing down your replace anyway.