TypeError: object of type 'float' has no len()
Andrew Henderson
What's going on here?
Here's the error:
for j in range(len(rotlati)):
TypeError: object of type 'float' has no len()The code is:
vv = np.matrix([0, 0]).T
rotlati = float(vv[0])
latidef = np.zeros(22)
for j in range(len(rotlati)): latidef[j] = rotlati[j] 0 5 Answers
The error is exactly what is says it is. rotlati is a float. You cannot take the len() of a float. Looking at your code, it looks as if you might have meant to create lists called rotlati and rotlongi and append to them on each iteration of your range(len(lati)) loop. Instead you're currently just overwriting the same two floating-point variables on every iteration.
The len argument may be a sequence (string, tuple or list) or a mapping (dictionary).
Before calling the len function, you should verify if the argument is one of this type. You can call the method isinstance() to verify it. Take a look on how to use it.
Another scenario i got the same error, while saving file.
odf.to_excel(writer,sheet_name=str(x),startcol=5,index=False)
You may also check the name of the sheet is int or float. Convert that to string.
It's common to get this error due to unexpected/"hidden" NaN values.
For example, suppose you have a list or a pandas Series (or any collection) of strings that was processed elsewhere and you want to find the length of each string. If this list contains a NaN, then the error in the title occurs.
lst = ['hello', float('nan'), 'hola'] # <---- has NaN
[len(x) for x in lst] # <---- TypeError: object of type 'float' has no len()You'll probably have your own way of handling these NaNs. For me, one way is to perform a conditional check and call len() only if it's not NaN.
For example, the below code finds the length of an element only if it equals itself (NaN doesn't equal itself) and do nothing otherwise.
[len(x) if x == x else x for x in lst]
# [5, nan, 4] I got the correct answer, try this:
lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0]
}
alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0]
}
tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0]
}
numbers = []
def average(numbers): total = float(sum(numbers)) return total / len(numbers)