Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert "%" str to float
#1
I am trying to write a program to calibrate the CIR model and when I was reading some data from a csv file and define a calculation, I get the error "could not convert string to float".However, the data in my csv file is presented in the form of "%".Like this:

Coupon
0.00%
0.00%
1.00%
2.25%
1.38%
1.63%
1.00%
1.00%
1.63%

I try to change the original data to number format, but it turns out the same error too.

Then I was stuck.Is there anyone who knows how to solve this problem?Thanks in advance for any help!
Reply
#2
what does the code look like?
show what you've tried so far
Reply
#3
[float(item.replace("%", "")) for item in data] should work. But if you prefer something a little more rad, here's a regex:
>>> import re
>>> data = '''Coupon
... 0.00%
... 0.00%
... 1.00%
... 2.25%
... 1.38%
... 1.63%
... 1.00%
... 1.00%
... 1.63%'''.split("\n")
>>> data
['Coupon', '0.00%', '0.00%', '1.00%', '2.25%', '1.38%', '1.63%', '1.00%', '1.00%', '1.63%']
>>> for row in data:
...   row = re.sub(r"[^\d\.]", "", row)
...   if row:
...     print(float(row))
...
0.0
0.0
1.0
2.25
1.38
1.63
1.0
1.0
1.63
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python calculate float plus float is incorrect? sirocawa 6 235 Apr-16-2024, 01:45 PM
Last Post: DeaD_EyE
  convert string to float in list jacklee26 6 1,897 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  openpyxl convert data to float jacklee26 13 5,935 Nov-19-2022, 11:59 AM
Last Post: deanhystad
  Convert SQLite Fetchone() Result to float for Math Extra 13 3,526 Aug-02-2022, 01:12 PM
Last Post: deanhystad
  Convert string to float problem vasik006 8 3,386 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  ValueError: could not convert string to float: RandomCoder 3 5,751 Jul-27-2020, 07:38 AM
Last Post: ndc85430
  could not convert string to float player1681 4 5,834 May-22-2020, 12:10 PM
Last Post: buran
  could not convert string to float: C JamesW 2 3,836 Jan-29-2020, 04:56 PM
Last Post: JamesW
  Error in the code ->ValueError: could not convert string to float: ' ' eagleboom 1 3,212 Nov-29-2019, 06:19 AM
Last Post: ThomasL
  ValueError: could not convert string to float: . BoaCoder3 3 124,054 Aug-24-2019, 06:26 AM
Last Post: atlass218

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020