Python error 'numpy.float64' object cannot be interpreted as an integer - python

I'm using Python3.x.
The bricks = [] the data is dataframe single element array which contains number and some negative numbers
for delta in data:
if delta > 0:
bricks.extend([1] * delta)
else:
bricks.extend([-1] * abs(delta))
The above code throws error, without affecting the outcome how to correct the code which will run without errors
The error here is:
bricks.extend([1] * delta) TypeError: 'numpy.float64' object cannot be
interpreted as an integer
Note :Community, before giving negative numbers, marked as duplicate provide a solution and then mark as you wish.

I think you should try
bricks.extend([1. * delta])
Considering that your "delta" is a simple value(numpyFloat or something like that) and you want to extend the list with a list of 1 value.

Related

Trouble in multiplying list of numbers converted from string to float in a loop (Python)

Here I am trying to multiply numbers stored in a list but in string type, showing this error
TypeError: can't multiply sequence by non-int of type 'float'
My list data sample
[5, 'BTCUSD', 'Sell', '9125.5', 6055, '0.66352527', 'Limit', 'Filled']
def calc():
num=0.0
den=0.0
for ids in listBox.selection():
num=num+(float(listBox.item(ids)['values'][3]*float(listBox.item(ids)['values'][4]))) #Problem occurng here
den=den+float((listBox.item(ids)['values'][4]))
print(listBox.item(ids)['values'])
print(num/den)
return 0
I might need more information about listBox,
but as I roughly see the given code, I think the line which caused error should be edited like below:
# Original Code:
# num=num+(float(listBox.item(ids)['values'][3]*float(listBox.item(ids)['values'][4])))
num=num+(float(listBox.item(ids)['values'][3])*float(listBox.item(ids)['values'][4]))
TypeError: can't multiply sequence by non-int of type 'float'
This occurs literally when you're trying to multiply a sequence(list, string, etc) with a float value like:
a = 'hello'
print(a * 3.0) # error
Multiplying a sequence by integer value is allowed, and it functions as repeating the sequence n times:
a = 'hello'
print(a * 3) # 'hellohellohello'
In your code, you didn't finished first float() function correctly. The second float() function is well done, so you were just trying to multiply a string (which is not converted yet) with a float value (which is converted well). Please inspect the parenthesis in your code carefully. Thanks.

'int' object is not callable error in python when taking cross-entropy of two lists

So I am getting an error called "TypeError: 'int' object is not callable" when I run this code. I did some research and I think it might be due to the fact that the cross entropy variable is declared as a wrong type. I would greatly appreciate some help on figuring out why I'm getting this error. Basically, what I'm doing is taking in two lists and trying to figure out the cross-entropy for the two lists through the code.
import numpy as np
# Write a function that takes as input two lists Y, P,
# and returns the float corresponding to their cross-entropy.
def cross_entropy(Y, P):
Y = np.float_(Y)
P = np.float_(P)
crossentropy = 0.0
for i in range(len(Y)):
crossentropy+=-1(Y[i]*np.log(P[i]) + (1-Y[i])*np.log(1-P[i]))
return crossentropy
Your code and computation has several issues beyond the problem you're asking about, but the main issue is this:
x = 10
-1(x)
This does not work, you need to specific the multiplication, as -1(x) in Python means "call -1 (as a function) with the argument x".
I.e.:
crossentropy += -1 * (Y[i]*np.log(P[i]) + (1-Y[i])*np.log(1-P[i]))
Note that afterwards, you are likely to get warnings about divisions by zero, depending on the inputs of the function.
The line
crossentropy+=-1(Y[i]*np.log(P[i]) + (1-Y[i])*np.log(1-P[i]))
has a 1 that is being treated as a function (ie “being called”). Try removing this integer, and the summation should work.

Consistent Type Error regarding converting a string to a float in Python

I am working on an assignment for an Introduction to Programming course and would like some direction as to what I am missing and why I continue getting the same TypeError. I am able to assign my strings however when I try to convert them to a float I end with a TypeError. I am pretty new to programming and coding in general so please don't be too harsh. I understand that it is probably something really obvious.
I have attempted to define the variable and convert it to a float from a string both prior to the calculation when I was setting up my inputs as well as during calculation of what the algorithm is attempting to execute.
enter_quizzes_weight = input("quizzes weight")
enter_quizzes_average = input('quizzes average')
quizzes_grade = float(enter_quizzes_weight * enter_quizzes_average)
The expected result is supposed to be the output of converting the strings to floats and then multiplying enter_quizzes_weight and enter_quiz_average however the actual result ends in the following error,
"TypeError: can't multiply sequence by non-int of type 'str'"
quizzes_grade = float(enter_quizzes_weight * enter_quizzes_average)
That code multiplies two variables and then converts the result to a float.
But you're doing the float conversion too late, because those two variables are strings, and you can't multiply strings.
You need to convert the variables to floats before multiplying:
quizzes_grade = float(enter_quizzes_weight) * float(enter_quizzes_average)
This should do:
enter_quizzes_weight = float(input("quizzes weight"))
enter_quizzes_average = float(input('quizzes average'))
quizzes_grade = (enter_quizzes_weight * enter_quizzes_average)
You're turning the strings you get from input("quizzes weight") and input('quizzes average') into floats, and then you multiply them

TypeError: object of type 'int' has no len() *subtraction*

I'm trying to figure out if there's a way to make a small calculation by subtracting a variables number from 4
number_1_raw = random.randrange(1, 1000)
number_1_len = len(number_1_raw)
number_of_zeros = 4 - number_1_len
print("0" * number_of_zeros + number_1_raw)
I wanted the script to give me an answer that ranged from 1-3, however the
code isn't executing properly.
The desired output would be something like this:
0617 or 0071 or 0008, etc.
Please help with this issue, thanks!
You cant call len on an integer.
The len() function returns the number of items in an object.
When the object is a string, the len() function returns the number of
characters in the string.
so what you can do is
number_1_len = len(str(number_1_raw))
str changes int type to string type.
This line number_1_len = len(number_1_raw)  is problem. You are getting an integer value as number_1_len, and it has length of one. This number_1_len is actually the number of zeros that you want
I think you need:
import random
number_1_raw = random.randrange(1, 1000)
number_1_len = len(str(number_1_raw))
number_of_zeros = 4 - number_1_len
print(number_of_zeros)
result = "0" * number_of_zeros
print(result+str(number_1_raw))
Output
1 # number of zeros
0801
What's wrong with your code
You are trying to find length of an integer number_1_raw which is giving you the error as you need iterables or string to find a length of that object. First convert it into string and then use len on it.
Furthermore, in print statement you need to convert number_1_raw into string so that it can be appended. You can not perform + operation on str and int.
I added the str() in a specific line so that your code runs without any error
import random
number_1_raw = str(random.randrange(1, 1000)) #I added the str() in this line
number_1_len = len(number_1_raw)
number_of_zeros = 4 - number_1_len
print("0" * number_of_zeros + number_1_raw)
it is completely your code except that modified line bro.
You had coded well bro but a small datatype mistake only you can rectify them as you learn.
i hope this is useful :)
First of all, I need to understand better what is happening...
Fist
number_1_raw = random.randrange(1, 1000)
The random.randrange returns a number, probably int.
Second
number_1_len = len(number_1_raw)
Has a problem, because number_1_raw is an int and len is a function that counts the number of elements from an array, an object... but number_1_len isn't... that's an int and len can't count an int element...
Is important you show all which error you're getting... and explain better what you're trying to do...

Python: "unsupported operand types for +: 'long' and 'numpy.float64' "

My program uses genetic techniques to build equations.
It randomly assembles strings into an equation with one unknown.
"(((x + 1) * x) / (4 * 6) ** 2)"
One of the strings is: "math.factorial(random.randint(1,9))"
So an equation is typically something like:
"(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9))"
Fifty different equations are generated and then assigned a fitness value according to
how well they approximate the sin function over a range of values.
for x in numpy.arange(1,6.4,.1):
fitness += abs(eval"(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9)) - numpy.sin(x))")
The program often throws an exception which is caught by an 'except TypeError' clause.
The error message is "unsupported operand types for +:'long' and 'numpy.float64'"
When I try "type(numpy.sin(1))"it returns
type: numpy.float64
How do I get 'long' and 'numpy.float64' operand types to work together?
Any help would be appreciated.
#catchmeifyoutry: good idea! Unfortunately it's a heck of an equation. I've never
tried to take one this long apart. I have wondered if there is a parsing utility to help
resolve all the brackets.
(((math.factorial(random.randint(1,9))))-(((x)+((((math.factorial(random.randint(1,9))))**((math.factorial(random.randint(1,9)))))-(((6.0)/(((8.0)/(((3.0)-(8.0))/(((5.0)*((2.0)/(x)))/(8.0))))+(4.0)))/(8.0))))+(7.0)))
I'll try to catch the value of x at which it failed.
First, you are missing a closing bracket in your example, and the (+ or - or / or * or **) is confusing.
What are you trying to achieve?
Do you just want to insert the result in the string?
Try this:
for x in numpy.arange(1,6.4,.1):
s = "sinus %f is %f!" % (x, numpy.sin(x))
print type(s), s
See string formatting documentation.
EDIT
Ah yes, genetic programming, that explains what you're trying to do ;)
Based on your updated information, I have to guess that your string construction is sometimes faulty somehow.
Change your code to display the string that causes the exception to be thrown. Easiest way is to just print the string before calling eval on it, and when the exception is thrown you can see what the last equation was.
Then, if it is not clear what is wrong with it, you can post that equation here.
This works for me:
for x in numpy.arange(1,6.4,.1):
eval("( 1 + (2 * 3) / 4 ) * numpy.sin(x)")

Categories