I still get a:
ValueError: invalid literal for float(): 002Q
when I try to:
df.column_name.astype(np.float64)
even after doing this on my column:
def convert_float(x):
try:
return np.float64(x)
except ValueError:
return np.NaN
df.column_name.apply(convert_float).astype(np.float64)
I also looked in the data manually, but could not find any value 002Q
Related
Suppose that I have a variable initial_cash = 'a'. I want to check if this is convertible to float else I want to raise error for that I've written code below:
initial_cash = 'a'
try:
initial_cash = float(initial_cash)
except TypeError:
raise TypeError("Initial cash amount should be float or int")
I am unable to raise exception instead I get ValueError: could not convert string to float: 'a'. What am I doing wrong due to which the expectation is not caught?
Your answer is in the error message - ValueError. you should expect ValueError instead of TypeError.
I have been trying to change an object to string, so i first did the below code
total_deliveries_data.Order_ID = map(lambda x : x.str.split('-').str[1].str.split(',').str[0], total_deliveries_data.Order_ID)
total_deliveries_data
when i try the below code to convert the column to in.
total_deliveries_data["Order_ID"] = total_deliveries_data["Order_ID"].astype(str).astype(int)
i get
ValueError: invalid literal for int() with base 10: '<map object at 0x7f9f1f678f10>'
How can i sort this out
I am required to write a function that takes a simple mathematical formula as a string as an argument. The function should then return the result of that formula. For example, for the input "2 + 3" the function should return 5.
A string is considered a valid formula if it has the format . Note that operator and integer are separated by whitespace.
A valid operator is either +, -, * or /
If a string doesn't consist of three parts (integer operator integer), the function should raise a ValueError with the message "Formula must be of the following format: ."
If the first part or the last part of the input string can't be converted to integers, the function should raise a ValueError with the message "Expected two integers."
If the second part of the string is not one of the valid operators, the function should raise a ValueError with the message "Invalid operator ''. Expected one of these operators: +, -, *, /."
If the second integer is zero and the operator is /, the function should raise a ZeroDivisionError with the message "Division by zero not possible."
So far I've managed to split the string by whitespace and convert the [0] and [2] indexes to integers to be used in solving the respective mathematical equations, and I've also written a try: except: block that successfully catches invalid operators and returns the desired error message. My problem is going on to accommodate the other exceptions as outlined in the conditions, although I've written code that attempts to catch the exceptions and print the relevant error messages, it isn't working and I'm still getting the default internal python error messages. I'm assuming something in my approach is off, maybe the order that the try: except blocks are written in? something with the indenting? I'm new to this so any pointers or advice would be much appreciated.
def formula_from_string(formula):
valid_operators = '+-*/'
chopped=formula.split()
equa=int(chopped[0]),chopped[1],int(chopped[2])
subtraction=equa[0]-equa[2]
addition=equa[0]+equa[2]
division=equa[0]/equa[2]
multiplication=equa[0]*equa[2]
if chopped[1]=='+':
return(addition)
elif chopped[1]=='-':
return(subtraction)
elif chopped[1]=='*':
return(multiplication)
elif chopped[1]=='/':
return(division)
try:
if chopped[1] not in valid_operators:
invalid=chopped[1]
raise ValueError
except ValueError:
print('Value Error:')
return("Invalid operator '"+invalid+"'. Expected one of these operators: +, -, *, /.")
try:
if chopped[0] or chopped[2] != int:
raise ValueError
except ValueError:
print('Value Error:')
return('Expected two integers.')
try:
if equa[1]=='/' and equa[2]==0:
raise ZeroDivisionError
except ZeroDivisionError:
print('ZeroDivisionError:')
return('Division by zero not possible.')
try:
if chopped <=1 or chopped >=2:
raise ValueError
except ValueError:
print('ValueError:')
return('Formula must be of the following format: <integer> <operator> <integer>.')
This code should helps you.
learn about Regex (Regular Expressions)
See Regular expression operations
import re
def formula_from_string(formula):
valid_operators = '+-*/'
pattern = re.compile(r'^(\d+)(?:\s+)?([*/+\-^])(?:\s+)?(\d+)$')
try:
if match := pattern.search(formula):
operator = match.group(2)
if operator not in valid_operators:
raise ValueError(f"Invalid operator {repr(operator)}. Expected one of these operators: +, -, *, /.")
else:
raise ValueError('Formula must be of the following format: <integer> <operator> <integer>.')
return eval(formula) # Safe call
except (ValueError, ZeroDivisionError) as e:
print(e)
# Uncomment to see output
# formula_from_string('3 / 2') # 1.5
# formula_from_string('3 ^ 2') # ValueError Invalid operator
# formula_from_string('a / 2') # ValueError Formula must be...
# formula_from_string('3 / 0') # ZeroDivisionError
I wrote a function that gets an argument, that should be a string, Now the function should know what is the data type of what in the string; Let's Say an example: -
def input_type(value):
pass
print(input_type("1"))
now the function should return the type is an integer
I need this with string type and float type and integer type.
For this specific question one could do this:-
def input_type(value):
if isinstance(value, str):
try:
int(value)
return 'int'
except ValueError:
pass
try:
float(value)
return 'float'
except ValueError:
pass
return 'string'
print(input_type('1'))
print(input_type('1.5'))
print(input_type('abc'))
print(input_type(999))
This will output:-
int
float
string
None
How can I get the datatypes for datetime and time from a csv file:
with open(dataPath, newline='') as csvData:
reader = csv.DictReader(csvData, delimiter=';')
head = next(reader)
.
.
I have the following csv file:
"...."; "YEAR"; "TIME"; "..." --> head
"...."; "19.05.2020"; "0050"; "..." --> "0050" means 00:50
"...."; "12.05.2020"; "2035"; "..." --> "2035" means 20:35
I tried it with a function:
def convert(value):
heuristics = [lambda value: datetime.strptime(value, "%d.%m.%Y"), datetime.strptime(value, "%H%D"), int, float]
for type in heuristics:
try:
return type(value)
except ValueError:
continue
# All other heuristics failed it is a string
return value
if I have a value "[1,2,3]" it outputs a valueerror but for this I wrote except ValueError: continue, why does it not continue when this error occure, same with "513165"
thanks
If you want to get this working, a few things:
you'll need a lambda for both strptime operations
%D is not a valid strptime directive, I assume you meant %M
don't redefine the built-in type
better catch and print the error, to know what's going on
working example with some tests (don't assume full coverage of any possible error though...)
def convert(value):
heuristics = [lambda value: datetime.strptime(value, "%d.%m.%Y"),
lambda value: datetime.strptime(value, "%H%M"),
int,
float]
for f in heuristics:
try:
return f(value)
except ValueError as e:
print(f"encountered error: {e}")
continue
# All other heuristics failed it is a string
return value
for v in ('2355', 'asdf', '12', '3.14', '7.12.2013'):
print(f"testing '{v}'...")
result = convert(v)
print(result, type(result))
giving you
testing '2355'...
encountered error: time data '2355' does not match format '%d.%m.%Y'
1900-01-01 23:55:00 <class 'datetime.datetime'>
testing 'asdf'...
encountered error: time data 'asdf' does not match format '%d.%m.%Y'
encountered error: time data 'asdf' does not match format '%H%M'
encountered error: invalid literal for int() with base 10: 'asdf'
encountered error: could not convert string to float: 'asdf'
asdf <class 'str'>
testing '12'...
encountered error: time data '12' does not match format '%d.%m.%Y'
1900-01-01 01:02:00 <class 'datetime.datetime'>
testing '3.14'...
encountered error: time data '3.14' does not match format '%d.%m.%Y'
encountered error: time data '3.14' does not match format '%H%M'
encountered error: invalid literal for int() with base 10: '3.14'
3.14 <class 'float'>
testing '7.12.2013'...
2013-12-07 00:00:00 <class 'datetime.datetime'>