Issue
Method 1 : Error : ufunc 'add' did not contain a loop with signature matching types dtype('
x = numpy.array(x)
x_5= x + 5
Method 2 : Error : must be str, not int
x_5 = [x+5 for x in x]
Method 3 : Error : invalid literal for int() with base 10: '-0.081428368' I tried to convert the x data first to integer
x_int = list(map(int, x))
x_5 = [x+5 for x in x]
method 4 : Error : 'numpy.float64' object is not iterable
x = numpy.array(x, dtype=float)
x = numpy.array(x)
x_piu_5= x + 5
Method 5 : Error : float object is not iterable
x_piu_5=[]
xfl=[float(i) for i in x]
x_piu_5[:] = [x + 5 for x in xfl]
Hi All
I am trying to add an integer number to my list which contains a lot of numbers like 0.00085695 , etc, and I have used two methods but I have been unsuccessful
Update 1 : Added method 4 , I have obtained the values I wanted, but the problem now is that it say the numpy.float is not iterable
Update 2 : Added method 5, Should I convert the float to string before iteration ?
Solution
The core of your problem is that your list x
contains strings representing floating-point numbers. You need to convert those strings to float
objects.
More precisely:
Method 1 can be fixed by using
dtype=float
, as suggested on the comments:x = numpy.array(x, dtype=float) x_5 = x + 5
Method 2 can be fixed by converting the items of
x
to float values before adding 5:x_5 = [float(i) + 5 for i in x]
Method 3 can be fixed by using
float
instead ofint
, as your values are not integers but rather floating-point values:x_float = list(map(float, x)) x_5 = [i + 5 for i in x_float]
Note that this solution is equivalent to method 2, just a bit slower and more space consuming, as you are creating an additional list.
Method 4 can be fixed by removing the spurious
x = numpy.array(x)
line. You will end up with the same code as method 1.As for method 5, I suspect that
x
is not the usual list, but rather it's a float object.
Other than converting values to the correct type, another thing you should try is to use different variable names for different things. In your code snippets, you're using x
both for your lists/arrays and for the elements of those lists. While it's not always strictly required, using different variable names would solve a lot of confusion and save you from many headaches!
Answered By - Andrea Corbellini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.