I am trying to compare the value I get from np.max(err) and np.min(err) to a float number, and I can't for the life of me figure out how to do it.
I've tried converting them to float by using the float() function, but that got me:
IndexError: invalid index to scalar variable.
Code:
err = [evaluation[i] - Ytest_set[i] for i in range(len(evaluation))]
if (0-float(np.min(err)))<0.05 & (0-float(np.max(err)))<0.05:
self.eval_pass = True
the goal is so for np.min(err) to be recognized as a float so that it can be compared to 0.05.
This much simpler code should be OK:
if -np.min(err)<0.05 and -np.max(err)<0.05:
self.eval_pass = True
If not, than you probably have a problem with the definition of err
BTW: as err is a list, you don't have to use np.min()\np.max(), and use the plain min()\min() instead.
Related
I would like to turn float integers (123.0) into ints (123).
What I would like the function to do:
Input: 2.1
Output: Exception, cannot turn float into int
Input: 2.0
Output: 2
Using int() on a float seems to just be math.floor() and that is not what I'm looking for.
You can check if after you use int() it the same value as the float
def convert(num):
if num == int(num):
return int(num)
raise Exception('Cannot turn float into int')
As a side note, using int() is not exactly as using math.floor(), try with negative numbers. What is the difference between int() and floor() in Python 3?
I don't know of a built-in that does it directly, but it is easy to create your own function. You can use .is_integer() on the input-value to check if the float is directly castable to int:
def strict_int(value):
if value.is_integer():
return int(value)
raise ValueError("cannot turn uneven float into int")
print(strict_int(3.0))
print(strict_int(3.1))
Output:
3
...
ValueError: cannot turn uneven float into int
But be warned, that there may be some unexpected behavior resulting from the way floats are represented. Try this for example:
print(strict_int(0.3 + 0.3 + 0.3 + 0.1))
This "1.0" will fail when trying to strictly convert to an int as it is in fact 0.9999999999999999! If you use the standard int it will work in that it gives you a result, but the result for int(0.3 + 0.3 + 0.3 + 0.1) is 0, probably not what you'd expect. But this is a general issue with how floats are represented and not directly related to the used methods. So you'll encounter this anywhere floats are present.
Here is an interesting post that goes a bit more into detail about the potential issues.
I guess i would just do
def convert(n):
return int(f"{n:g}")
I am working with graphs in python. I am trying to get the distance between each vertex. I need to use the value INFINITY (represented using the string "-") for a situation in which there is no direct path between one vertex and another. I tried a couple of solutions. One was using a crazy large int to represent infinity. However, I researched and found that this is poor practice. I also saw several solutions on stack overflow that made use of the math module's infinity function. However, this is not appropriate for my problem, as my INFINITY value is being used in a UI and must look graphically pleasing. This is why my INFINITY must remain as the string "-". This is the error I am getting with my current line of code:
TypeError: '<' not supported between instances of 'str' and 'int'
I am not completely sure, but I think the < is coming from my use of the min() function.
This error is coming from the following code:
for i in range(length):
for j in range(length):
for k in range(length):
#print('40:', int(temp[j][i]), int(temp[i][k]))
temp[j][k] = min(temp[j][k], addWithInfinity(temp[j][i],temp[i][k]))
Temp just refers to a matrix which I received as an argument in the method I am currently working with. Here is my addWithInfinity method:
def addWithInfinity(a, b):
"""If a == INFINITY or b == INFINITY, returns INFINITY.
Otherwise, returns a + b."""
if a == LinkedDirectedGraph.INFINITY or b == LinkedDirectedGraph.INFINITY:
return LinkedDirectedGraph.INFINITY
else: return a + b
My issue is that I am trying to compare infinity with an int. I tried to convert INFINITY to an int like this: int(INFINITY) ( or int('-') ) but I got the following error:
ValueError: invalid literal for int() with base 10: '-'
Any ideas how I can get away with the comparison between an int and INFINITY (which is a string)?
Use float("inf") or math.inf
See also How can I represent an infinite number in Python?
>>> float("inf") > 5
True
>>> float("inf") < 10**100
False
>>> import math
>>> float("inf") == math.inf
True
If you need to use some other value than "inf" for infinity, such as '-' in your example, you could try/except it, either
checking if the initial value is your target string (if a == '-':)
parsing the error calling float on it (if "'-'" in str(err_string):)
try:
a = float(a)
except ValueError as ex:
# special-case for ValueError: could not convert string to float: '-'
if "'-'" in str(ex).split(":")[-1]:
a = float("inf")
else: # re-raise other ValueErrors
raise ex
String "-" is not infinity even you mean it. In Python, you can obtain the type in two ways:
float("inf")
or
import math
math.inf
Your problem is not related to the usage or use cases of infinity type, but it is the representation issue. I believe you should use the normal infinity type in your math and create a property in your class that returns "-" and then use it only when you need to represent it on UI but not in your math.
The issue that you have is more about the decoupling of representation and logic.
I am extremely new to Python and I have tried searching for answers and debugging for days but I could not solve this issue. Please help me.
Main Question: How do I concatenate a zeros function, zeros((1,142)) with a float number, 1954.0 ?
Things I have tried:
Converting the float number, 1954.0 into an array using: numpy.array(1954.0)
Concatenate the zeros function with the converted float number: concatenate((zeros(1,142), numpy.array(1954.0)))
[It gave a ValueError: all the input arrays must have same number of dimensions]
I tried doing this instead: concatenate((zeros(1,142)), numpy.array([[1954.0]]))) and it gave a DIFFERENT ValueError message.
[ValueError: all the input array dimensions except for the concatenation axis must match exactly]
I have checked using: type(numpy.array(1954.0)) and it says <type 'numpy.ndarray'> and also checked using: type((zeros(1,142)) and it says <type 'numpy.ndarray'>. Both are of the same type, which means I should be able to concatenate but somehow it still gives me the various error messages shown in point 2 and 3.
I am desperately in need of help for this.
Nicer ways to accomplish this are
a = numpy.zeros((1,143))
a[0, -1] = 1954
or
a = numpy.append(numpy.zeros((1,142)), 1954)
Mike Graham's answer's are nicer but if you insist on using concatenate, then the following will work:
x = np.zeros( (1,143))
y = np.array([[1943]])
tot = np.concatenate((x,y), axis=1)
Does anyone know how to convert int to float.
For some reason, it keeps on printing 0. I want it to print a specific decimal.
sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / np.size(women_onboard)
print 'Proportion of women in class3 who survived is %s' % proportion_womenclass3_survived
To convert an integer to a float in Python you can use the following:
float_version = float(int_version)
The reason you are getting 0 is that Python 2 returns an integer if the mathematical operation (here a division) is between two integers. So while the division of 144 by 314 is 0.45~~~, Python converts this to integer and returns just the 0 by eliminating all numbers after the decimal point.
Alternatively you can convert one of the numbers in any operation to a float since an operation between a float and an integer would return a float. In your case you could write float(144)/314 or 144/float(314). Another, less generic code, is to say 144.0/314. Here 144.0 is a float so it’s the same thing.
Other than John's answer, you could also make one of the variable float, and the result will yield float.
>>> 144 / 314.0
0.4585987261146497
In Python 3 this is the default behavior, but if you aren't using that you can import division like so:
>>> from __future__ import division
>>> 144/314
0.4585987261146497
Alternatively you can cast one of the variables to a float when doing your division which will do the same thing
sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / float(np.size(women_onboard))
You can just multiply 1.0
>>> 1.0*144/314
0.4585987261146497
You can literally convert it into float using:
float_value = float(integer_value)
Likewise, you can convert an integer back to float datatype with:
integer_value = int(float_value)
Hope it helped. I advice you to read "Build-In Functions of Python" at this link:
https://docs.python.org/2/library/functions.html
The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.
The question asked is just a type conversion question and here its conversion from int data type to float data type and for that you can do it by the function :
float()
And for more details you can visit this page.
I have a file that has 3 values on each line. It is a fairly random file, and any of these values can be str or int.
George, 34s, Nikon
42, absent, Alan
apple, 111, 41
marked, 15, never
...
So, I read in the line, and using split I get the first value:
theFile = r"C:\... "
tDC = open(theFile, "r")
for theLine in tDC:
a, b, c = theLine.split(',')
So far so good.
Where I'm stuck is when I try to deal with variable a. I need to deal with it differently if it is a str or if it is an int. I tried setting a = int(a), but if it is a string (e.g., 'George') then I get an error. I tried if type(a) = int or if isinstance(a,int), but neither work because all the values come in as a string!
So, how do I evaluate the value NOT looking at its assigned 'type'? Specifically, I want to read all the a's and find the maximum value of all the numbers (they'll be integers, but could be large -- six digits, perhaps).
Is there a way to read in the line so that numbers come in as numbers and strings come in as strings, or perhaps there is a way to evaluate the value itself without looking at the type?
The first point is that you need some rule that tells you which values are integers and which ones aren't. In a data set that includes things like 32s, I'm not sure it makes sense to just treat anything that could be an integer as if it were.
But, for simplicity, let's assume that is the rule you want: anything that could be an integer is. So, int(a) is already pretty close; the only issue is that it can fail. What do you do with that?
Python is designed around EAFP: it's Easier to Ask Forgiveness than Permission. Try something, and then deal with the fact that it might fail. As Cyber suggests, with a try statement:
try:
intvalue = int(a)
except ValueError:
# Oops, it wasn't an int, and that's fine
pass
else:
# It was an int, and now we have the int value
maxvalue = max(maxvalue, intvalue)
isalpha() Returns "True" if all characters in the string are in the alphabet
isnumeric() Returns "True" if all characters in the string are numeric
so;
data="Hello World"
print(data.isnumeric()) #it will retuns with False
print(data.isalpha()) # True
Sorry for my soulles answer, I just came here for same issue, I found a different way and wanted to share with you
values = theLine.split(',')
for value in values:
try:
number = int(value)
# process as number
except ValueError:
# process value as string
this :
def ret_var(my_var: int) -> int:
try:
intvalue = int(my_var)
return my_var
except ValueError:
print("my_var not int!")