简体   繁体   中英

How to convert a string to float when the string has negative values in dataframe?

I have a dataframe which was read from an xls. It has two columns with numbers that were read in as strings, these columns also have negative values in them. I am trying to convert these strings to floats but am getting an error.

I tried to replace the string, what I thought was the issue (the '-') but I still get the error below:

ValueError: could not convert string to float: '-'

df2['VOL'] = df2['VOL'].str.replace('−', '-').astype(float)

I am expecting an output of floats without an error.

Replace t in the code bellow with df2['VOL'].

t = '−423'
t = float(t.replace('−', '-'))

print(t)

output

-423.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM