Could not convert string to float как исправить

Как исправить? Ошибка возникает когда я хочу превратить элемент из списка в число.

@bot.message_handler(commands=['convert'])
def cmd_convert(message):
    response = requests.get('https://yandex.ru/')
    page = response.text
    soup = BeautifulSoup(page, 'html.parser')
    currency = []
    for figures in soup.select('span.inline-stocks__value_inner'):
        currency.append(figures.text)
    try:
        class Converter:
            def __init__(self):
                self.usd = currency[0]
                self.eur = currency[1]
                self.rub = sum

            def dollar(self):
                return int(self.rub) / int(float(self.usd))

            def euro(self):
                return int(self.rub) / int(float(self.eur))

        def extract_arg(arg):
            return arg.split()[1:]

        answer = extract_arg(message.text)
        sum = int(answer[0])
        converter = Converter()
        sum1 = round(converter.dollar(), 2)
        sum2 = round(converter.euro(), 2)
        bot.send_message(message.chat.id, f'USD: {sum1}nEUR: {sum2}')
    except IndexError:
        bot.send_message(message.chat.id, 'Введите сумму после команды')

задан 20 окт 2020 в 14:43

jojo's user avatar

1

Ну, можно заменить , на . и будет работать. Так вот работает:

float('77,59'.replace(',','.'))

Ну, то есть у вас будет видимо:

int(float(self.usd.replace(',','.')))

USERNAME GOES HERE's user avatar

ответ дан 20 окт 2020 в 14:50

CrazyElf's user avatar

CrazyElfCrazyElf

65.4k5 золотых знаков19 серебряных знаков50 бронзовых знаков

4

Надо заменить , на . т.к. питон использует . для float:

@bot.message_handler(commands=['convert'])
def cmd_convert(message):
    response = requests.get('https://yandex.ru/')
    page = response.text
    soup = BeautifulSoup(page, 'html.parser')
    currency = []
    for figures in soup.select('span.inline-stocks__value_inner'):
        currency.append(figures.text)
    try:
        class Converter:
            def __init__(self):
                self.usd = currency[0]
                self.eur = currency[1]
                self.rub = sum

            def dollar(self):
                return int(self.rub) / int(float(self.usd.replace(',', '.')))

            def euro(self):
                return int(self.rub) / int(float(self.eur.replace(',', '.')))

        def extract_arg(arg):
            return arg.split()[1:]

        answer = extract_arg(message.text)
        sum = int(answer[0])
        converter = Converter()
        sum1 = round(converter.dollar(), 2)
        sum2 = round(converter.euro(), 2)
        bot.send_message(message.chat.id, f'USD: {sum1}nEUR: {sum2}')
    except IndexError:
        bot.send_message(message.chat.id, 'Введите сумму после команды')

ответ дан 20 окт 2020 в 14:50

USERNAME GOES HERE's user avatar

USERNAME GOES HEREUSERNAME GOES HERE

10.3k21 золотой знак24 серебряных знака51 бронзовый знак

Pandas

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна распространенная ошибка, с которой вы можете столкнуться при использовании pandas:

ValueError : could not convert string to float: '$400.42'

Эта ошибка обычно возникает, когда вы пытаетесь преобразовать строку в число с плавающей запятой в pandas, но строка содержит одно или несколько из следующих:

  • Пространства
  • Запятые
  • Специальные символы

Когда это происходит, вы должны сначала удалить эти символы из строки, прежде чем преобразовывать ее в число с плавающей запятой.

В следующем примере показано, как устранить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'store': ['A', 'B', 'C', 'D'],
 'revenue': ['$400.42', '$100.18', '$243.75', '$194.22']})

#view DataFrame
print(df)

# store revenue
#0 A $400.42
#1 B $100.18
#2 C $243.75
#3 D $194.22

#view data type of each column
print(df.dtypes )

#store object
#revenue object
#dtype: object**

Теперь предположим, что мы пытаемся преобразовать столбец revenue из строки в число с плавающей запятой:

#attempt to convert 'revenue' from string to float
df['revenue'] = df['revenue'].astype (float)

ValueError : could not convert string to float: '$400.42'

Мы получаем ошибку, так как столбец revenue содержит в строках знак доллара.

Как исправить ошибку

Способ устранения этой ошибки заключается в использовании функции replace() для замены знаков доллара в столбце revenue ничем перед выполнением преобразования:

#convert revenue column to float
df['revenue'] = df['revenue'].apply(lambda x: float(x.split()[0].replace('$','')))

#view updated DataFrame
print(df)

# store revenue
#0 A 400.42
#1 B 100.18
#2 C 243.75
#3 D 194.22

#view data type of each column
print(df.dtypes )

#store object
#revenue float64
#dtype: object

Обратите внимание, что мы можем преобразовать столбец дохода из строки в число с плавающей запятой, и мы не получаем никаких ошибок, поскольку перед выполнением преобразования мы удалили знаки доллара.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить в Python: объект ‘numpy.ndarray’ не вызывается
Как исправить: TypeError: объект ‘numpy.float64’ не вызывается
Как исправить: ошибка типа: ожидаемая строка или байтовый объект

In Python, we can only convert specific string values to float. If we try to convert an invalid string to a float, we will raise the ValueError: could not convert string to float.

To solve this error, ensure you strip the string of invalid characters like commas, spaces or brackets before passing it to the float() function.

This tutorial will go through how to solve the error with the help of code examples.


Table of contents

  • ValueError: could not convert string to float 
  • Example
    • Solution
  • Example #2
    • Solution
  • Summary

ValueError: could not convert string to float 

In Python, a value is information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.

A string is a suitable type to convert to a float. But several string values are not suitable to convert to float:

  • A value that contains non-special terms, for example, ‘nan’ is a special term, “bread” is not.
  • A value that contains a commas, speech marks and other non alphanumeric characters.
  • A value that contains spaces.

We can convert inf and nan to floats because they represent specific floats in Python, namely infinity and NaN (Not a Number).

Example

Consider the following CSV file called money.csv that contains the epoch timestamp and money in two accounts.

"'1645916759'",20000,18000
"'1645916790'",21000,17000
"'1645916816'",20500,17250

Next, we will write a program that will read the information from the CSV file and print it to the console. We will import the csv library to read the CSV file. Let’s look at the code:

from datetime import datetime

with open("money.csv", "r") as money:

   readf = csv.reader(money)

   for line in readf:

       time = float(line[0])

       account_one = float(line[1])

       account_two = float(line[2])

       print(f'At date: {datetime.fromtimestamp(time)}, Account one value £{account_one}, Account two value £{account_two}')

We use the datetime library to convert the epoch timestamp to a date. Let’s run the code to see the result:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      2     readf = csv.reader(money)
      3     for line in readf:
----≻ 4         time = float(line[0])
      5         account_one = float(line[1])
      6         account_two = float(line[2])
ValueError: could not convert string to float: "'1645916759'"

The error occurs because the epoch timestamp contains inverted commas, which are invalid string values to convert to a float.

Solution

We need to strip the epoch timestamp of the inverted commas using the String strip() method to solve this error. Let’s look at the revised code:

from datetime import datetime

with open("money.csv", "r") as money:

   readf = csv.reader(money)

   for line in readf:

       time = float(line[0].strip("'"))

       account_one = float(line[1])

       account_two = float(line[2])

       print(f'At date: {datetime.fromtimestamp(time)}, Account one value £{account_one}, Account two value £{account_two}')

Let’s run the code to see the result:

At date: 2022-02-26 23:05:59, Account one value £20000.0, Account two value £18000.0
At date: 2022-02-26 23:06:30, Account one value £21000.0, Account two value £17000.0
At date: 2022-02-26 23:06:56, Account one value £20500.0, Account two value £17250.0

The code successfully prints each line in the money.csv file.

Example #2

Let’s look at an example, where we write a program that converts a weight from kilograms to pounds. First, we will ask a user to insert the weight in kilograms that they want to convert to pounds:

weight = float(input("Enter the weight to convert to pounds: "))

Next, we will define the conversion value to convert kilograms to pounds:

convert_to_lbs = 2.205

Then, we will attempt to convert the kilogram value to pounds and print the result to the console.

weight_in_lbs = weight * convert_to_lbs

print(f'{weight}kg is {weight_in_lbs}lbs')

Let’s run the code to see what happens:

Enter the weight to convert to pounds: 87,50
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
----≻ 1 weight = float(input("Enter the weight to convert to pounds: "))
ValueError: could not convert string to float: '87,50'

We raise the ValueError because the string we input contains a comma.

Solution

To solve the error we can use a try-except block. The program will try to run the code in the “try” block, if unsuccessful, the program will run the code in the “except” block. Let’s look at the revised code:

convert_to_lbs = 2.205

try: 

    weight = float(input("Enter the weight to convert to pounds: "))

    weight_in_lbs = weight * convert_to_lbs

    print(f'{weight}kg is {round(weight_in_lbs,1)}lbs')

except:

    print('Please insert a valid weight. The weight cannot contain commas, spaces or special characters')

Let’s try the code and input an invalid string:

Enter the weight to convert to pounds: 87,50
Please insert a valid weight. The weight cannot contain commas, spaces or special characters

We see that the program executes the print statement in the except block. Let’s run the code and input a valid string:

Enter the weight to convert to pounds: 87.50
87.5kg is 192.9lbs

The code successfully executes the code in the try block and prints the kilogram and the converted pound value to the console.

Summary

Congratulations on reading to the end of this tutorial! The error ValueError: could not convert string to float occurs if you try to convert a string to a float that contains invalid characters. To solve this error, check the string for characters that you can remove and use the strip() method to get rid of them. If a value has a comma instead of a decimal point, you can use replace() to replace the comma.

You can also use a try-except statement to catch the ValueError and pass. This method is useful if you are taking input from a user.

For further reading on ValueErrors, go to the articles:

  • How to Solve Python ValueError: list.remove(x) x not in list
  • How to Solve Python ValueError: year is out of range

For further reading on converting values, go to the article: How to Solve Python TypeError: int() argument must be a string, a bytes-like object or a number, not ‘list’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

In this Python tutorial, we will discuss how to fix an error, “Could not convert string to float Python“.

In python, to convert string to float in python we can use float() method. It can only convert the valid numerical value to a floating point value otherwise it will throw an error.

Example:

my_string = '1,400'
convert = float(my_string)
print(convert)

After writing the above code (could not convert string to float python), Ones you will print ” convert ” then the output will appear as a “ ValueError: could not convert string to float: ‘1,400’ ”.

Here, we get the error because the value is not valid and we used a comma. You can refer to the below screenshot could not convert string to float python.

Could not convert string to float python
Could not convert string to float python

To solve this ValueError: could not convert string to float we need to give the valid numerical value to convert my string to float by using float() method.

Example:

my_string = '23.8'
convert = float(my_string)
print(convert)

After writing the above code (could not convert string to float python), Ones you will print ” convert ” then the output will appear as a “ 23.8 ”. Here, the float() method converts the string to float. You can refer to the below screenshot could not convert string to float python.

Could not convert string to float python
Could not convert string to float python

This is how to fix could not convert string to float python.

Read: Python find substring in string

How to fix could not convert string to float python

Let us see how to fix could not convert string to float python

In this example, we got a ValueError because the function argument is of an inappropriate type. So, when we tried to typecast a string value it throws ValueError.

Example:

str = "Hi"
print(float(str))

The normal text is not supported by the float() function in python. You can refer to the below screenshot for the error.

How to fix could not convert string to float python
How to fix could not convert string to float python

To fix value error: could not convert string to float python, we have to give numeric text value to convert it successfully to float. we can use the below code to solve the above error.

Example:

str = "5.45"
print(float(str))

You can refer to the below screenshot to see the output for how to fix could not convert string to float python.

How to fix could not convert string to float python
How to fix could not convert string to float python

You may like the following Python tutorials:

  • How to handle indexerror: string index out of range in Python
  • How to convert an integer to string in python
  • Slicing string in Python + Examples
  • Convert string to float in Python

Here we checked how to fix error, could not convert string to float python.

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Table of Contents
Hide
  1. ValueError: could not convert string to float
  2. Exception could not convert string to float
  3. Fix ValueError: could not convert string to float
  4. Solution 1: Ensure the string has a valid floating value
  5. Solution 2: Use try-except

If you convert a string object into a floating-point in Python many times you will get a ValueError: could not convert string to float. Usually, this happens if the string object has an invalid floating value with spaces or comma Python will throw ValueError while parsing into string object into float.

In this article, we will take a look at what this error means and how to fix this error in your code with examples.

If we are reading and processing the data from excel or CSV, we get the numbers in the form of a string, and in the code, we need to convert from string to float

Python has a built-in float() method that can parse the string to a floating-point number. This method will be useful when we need to perform a mathematical operation on a string object.

The float() method only allows you to convert strings that hold float-like numbers. This means that you cannot convert a value if 

  • A value contains spaces
  • A value contains a comma
  • A value contains special characters 

Exception could not convert string to float

order_value = '12,000'
tax_percentage = 4

tax_amount = (float(order_value)*(tax_percentage / 100))
print("The total tax amount is ", tax_amount)

Output

Traceback (most recent call last):
  File "c:/Projects/Tryouts/main.py", line 4, in <module>
    tax_amount = (float(order_value)*(tax_percentage / 100))
ValueError: could not convert string to float: '12,000'

Let’s take a simple example to demonstrate the ValueError exception. In the below code, we have the total order value in terms of USD, and we are accepting this in string format and performing a tax calculation.

If you see the above code, the order value has a comma-separated numeric value, and while parsing into a float, Python will throw ValueError: could not convert string to float.

There are a few other scenarios where you could get ValueError.

  1. Converting an empty string into a floating-point number
  2. Converting a non-floating string to a floating-point number

Fix ValueError: could not convert string to float

There are multiple ways to resolve the issue. Let’s take a look at each of the solutions.

Solution 1: Ensure the string has a valid floating value

The easiest way is to clean up the data or pass it in the correct format if we already know the data format before converting it into float. 

If the value has a comma, space, or any special characters, then it needs to be processed before converting into float. 

In the below code, we are storing a valid float number as a string, and later we are converting that into floating-point to calculate tax.

Example:

order_value = '12000'
tax_percentage = 4

tax_amount = (float(order_value)*(tax_percentage / 100))
print("The total tax amount is ", tax_amount)

Output

The total tax amount is  480.0

Solution 2: Use try-except

The best way is to handle the exception in case of an invalid data format. In the below code, it will run the code in the try block. If the conversion fails, then it runs the except block code.

Example:

order_value = '12,000'
tax_percentage = 4

try:
    tax_amount = (float(order_value)*(tax_percentage / 100))
    print("The total tax amount is ", tax_amount)
except:
    print ("Order value is invalid")

Output

Order value is invalid

Ezoic

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Добавить комментарий