Reputation: 688
I have the code below which takes a list of coefficients which are floats and I want to turn the ones that are actually integers, to integers (for example 2.0 I want to become just 2).
So I have the code below and the output of the 3 print functions are:
[ 0. 0. -0. 0. -0. -0. -0. 0. 0.5 0. ]
,
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
and
[ 0. 0. 0. 0. 0. 0. 0. 0. 0.5 0. ]
.
So based on the printing, it enters the "if" statements, which means it confirms that my coefficients are actually integers (I have also tried "is_integer" function, getting the same result), but for some reason it doesn't convert them to integers. Can somebody help me with this? Thank you!
def function(coeffs):
coeffs = np.round(coeffs,2)
print(coeffs)
for w in range(len(coeffs)):
if coeffs[w]-int(coeffs[w])==0.0:
coeffs[w] = int(coeffs[w])
print(coeffs[w])
print(coeffs)
Upvotes: 0
Views: 92
Reputation: 654
This would be a great place to use list comprehension. I am not quite sure why the code you've given does not work, but I can give you the code which would make it work.
coeffs = [int(x) if x.is_integer() else x for x in coeffs]
This line goes through your coeffs array and for every x, it checks if it is an integer with the is_integer()
function you mentioned. If it is, int(x)
is added, else the float itself is added.
Upvotes: 0
Reputation: 868
You can add a type-checking condition in the loop, such as
if int(coeffs[w]) == coeffs[w]
, because I suspect it will be more robust as a solution.
Also, I'd suggest creating a new list or using a lambda, as modifying a list (or in this case, a numpy
array, which has a set data type) at the same time as you're accessing it, generally poses traps.
The following should work nicely.
new_coeffs = []
def function(coeffs):
coeffs = np.round(coeffs,2)
print(coeffs)
for w in range(len(coeffs)):
if int(coeffs[w]) == coeffs[w]:
new_coeffs.append(int(coeffs[w]))
else:
new_coeffs.append(coeffs[w])
print(new_coeffs)
This produces the following result, which I suspect is what you require.
>>> new_coeffs = []
>>> a = [1.0, 2.0, 4.1, -8.0, -1.3]
>>> function(a)
[ 1. 2. 4.1 -8. -1.3]
[1, 2, 4.1, -8, -1.3]
Upvotes: 0
Reputation: 3570
One way to do this is to check if both ceil
and floor
functions return the same value. For such floats should be same.
import math
...
for w in range(len(coeffs)):
if math.floor(coeffs[w]) == math.ceil(coeffs[w]):
print(int(coeffs[w]))
Upvotes: 0
Reputation: 590
Your data looks like it is probably coming in as a numpy array, with a float dtype. You are assigning integers back into this numpy float array. This will not change the type of individual entries, as numpy arrays have just one type for the all entries in the array.
You could produce a new Python list with the results in.
Something like this works:
result = [ int(x) if x-round(x)<0.0001 else x for x in np.array([1.1, 2.0, 3]) ]
Upvotes: 1