I keep getting the error: ‘float’ object has no attribute ‘append’
I’m unsure where to start as it was working before, but when I went to run my code, I keep getting the float error. The code worked before I changed the initial time to 1 and then back to 0 to play around with it.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import math
# define da/dt = (u-a)/(tau(a,u))
t0 = 0 #inital time in microseconds
a0 = 0.0 # excitation in volts
tf = 10 # final time in microseconds
dt = 0.1 # time step size
t_act = 0.75
t_deact = 0.25
#u = 1.0 # inital excitation value in volts - fix excitation
n = int((tf-t0)/dt+1) #number of samples
# defining t values
t = np.linspace(t0,tf,num=n)
# initalizing array for a and u values
a = np.zeros([n])
#excitation signal allocation
for i in range(1,10):
u.append(1)
for i in range(11,3000):
u.append(0)
# loop for euler's method
a[1] = a0
for i in range(1,n):
a[i] = a[i-1] + dt * (((u[i])/t_act) + ((1 - u[i])/t_deact) * (u[i] - a[i-3]))
# plot solution
plt.plot(t,a, 'o')
plt.xlabel("Value of t in ms")
plt.ylabel("Value of excitation in ")
plt.title("Activation Dynamics")
plt.show()
I expect to plot t & a, but I’m unsure what to do now.
I have read all the script from default dict and all the posts on here. I believe my syntax is correct.
influenceDict = defaultdict(list)
to fill with all tags from all tweets
Later, I am appending ALOT of float values, 1000+ list entries for a majority of dictionary keys. I get my error on line 47, specified below.
def addInfluenceScores(hashtagArr,numFollowers,numRetweets, influenceDict):
influenceScore = float(0)
if numFollowers == 0 and numRetweets != 0:
influenceScore = numRetweets + 1
elif numFollowers == 0 and numRetweets == 0:
influenceScore = 0
else:
influenceScore = numRetweets / numFollowers
print "Adding influence score %f to individual hashtags" % (influenceScore)
for tag in hashtagArr:
tID = tag2id_map[tag]
print "Appending ",tID,tag
# if not influenceDict.has_key(tID):
# influenceDict[tID] = list()
# influenceDict[tID].append(influenceScore)
# else:
# influenceDict[tID].append(influenceScore)
influenceDict[tID].append(influenceScore) **#LINE 47 I GET THE ERROR HERE**
for i in range(len(hashtagArr)):
for j in range(i+1, len(hashtagArr)):
tID1 = tag2id_map[hashtagArr[i]]
tID2 = tag2id_map[hashtagArr[j]]
if(tID2 < tID1): #ensure alpha order to avoid duplicating (a,b) and (b,a)
temp = tID1
tID1 = tID2
tID2 = temp
print "Appending ",tID1, hashtagArr[j],tID2,hashtagArr[i]
# if not influenceDict.has_key((tID1, tID2)):
# influenceDict[(tID1, tID2)] = list()
# influenceDict[(tID1, tID2)].append(influenceScore)
# else:
# influenceDict[(tID1, tID2)].append(influenceScore)
influenceDict[(tID1, tID2)].append(influenceScore)
The program runs for a while, and it actually does append values (or so I think) and then I get this error:
Traceback (most recent call last):
File "./scripts/make_id2_influencescore_maps.py", line 158, in <module
processTweets(tweets, influenceDict)
File "./scripts/make_id2_influencescore_maps.py", line 127, in processTweets
addInfluenceScores(hashtags, numFollowers,numRetweets, influenceDict)
File "./scripts/make_id2_influencescore_maps.py", line 47, in addInfluenceScores
influenceDict[tID].append(influenceScore)
AttributeError: 'float' object has no attribute 'append'
I am thinking that the list is just maxed out in memory. Maybe you guys can see something I don’t. I am trying to loop through a file of tweets and for everytime I see the hashtag I want to append a score to the list associated with it. That way I can just take the average of all the scores in the list when I am completely done reading the file. Thanks ahead.
#python #python-3.x #dictionary
#python #python-3.x #словарь
Вопрос:
Попытка добавить значения с плавающей запятой к тому же ключу в словаре типов defaultdic.
from collection import defaultdict
new_dict= defaultdict(list)
for row in list_dict:
acct=row[acct]
time_spent= float(row[time_spent])
if (acct not in new_dict):
new_dict[acct] = time_spent
else:
new_dict[acct].append(time_spent)
выдает ошибку:
AttributeError: 'float' object has no attribute 'append'
Если я удалю float,
time_spent= float(row[time_spent])
дает мне,
AttributeError: 'str' object has no attribute 'append'
Я должен добавить эти time_spent в список значений позже, поэтому я бы хотел, чтобы они были с плавающей точкой.
Ответ №1:
Когда acct
это не так new_dict
, вы присваиваете новому ключу значение с плавающей запятой ( time_spent
). Поскольку вы используете a defaultdict
, который автоматически создаст пустое list
значение при первом чтении ключа, вы должны удалить проверку и безоговорочно append
новое значение:
time_spent= float(row[time_spent])
new_dict[acct].append(time_spent)
Here is what you might be looking for…
def improve_list(ls, average):
for i in range(len(ls)):
if ls[i] < average:
ls[i] = average
return ls # Returns the improved list.
ls = [10.50, 11.40, 20.50, 9.30, 5.00]
total = 0.0
average = 0.0
for num in ls:
total += num
average = total / len(ls)
print("Original list: {}".format(ls))
improved_list = improve_list(ls, average) # Stores the improved list in a variable.
print("Improved list: {}".format(improved_list))
Although Python is a very easy language to learn for beginners, it occasionally throws a confusing error, one of which is AttributeError: ‘float’ object has no attribute ‘#’ in Python. If you’re getting this error and don’t know what’s causing it. Read this article to learn more about this error.
Every object in Python has attributes and methods that can be accessed using the dot notation. For example, the list object has methods like append, insert, remove, sort, etc. And you can access them using a syntax like this: list.append()
.
If you see the error above, it means you’re attempting to access an attribute or function that does not exist for the float data type. This can happen if you type the attribute or method name incorrectly. Consider the following example.
number = 9.9 # Trying to use append() on a floating number print(number.append('9'))
Error:
AttributeError: 'float' object has no attribute 'append'
As you can see, because the floating object has no append()
function, Python throws the above error.
This error can also be caused by typos, as shown below:
number = 9.9 # Type 'floor' but mistake it for 'flor' print(number.__flor__())
Error:
AttributeError: 'float' object has no attribute '__flor__'
How to avoid the AttributeError: ‘float’ object has no attribute ‘#’ in Python?
Using the hasattr()
function
The hasattr() function checks whether an object has the given attribute. It returns True if the object has the given attribute. Otherwise, it returns False.
To avoid this error, use hasattr()
to see if the attribute you need exists in the floating object before using it. As an example:
number = 9.9 # Check the append attribute using hasattr() if hasattr(number, 'append'): number.append('9') else: print("There is something wrong here. The floating object has no this attribute!")
Output:
There is something wrong here. The floating object has no this attribute!
Using the try…except
We can also use a try … except block to handle our AttributeError. This will allow our code to continue running even if an error occurs.
In this case, we’ll try to do something (access the attribute), and if it fails (causes an AttributeError), we’ll do something else instead. Like this:
number = 9.9 # Handle the AttributeError using the try...except block try: number.append('9') print(number) except AttributeError: print("There is something wrong here. Make sure you're using the appropriate attribute on the object!")
Output:
There is something wrong here. Make sure you're using the appropriate attribute on the object!
Using the dir()
function
The dir()
function is used to get a list of an object’s attributes and methods. This can be useful for debugging, as it can help us see what attributes an object has and doesn’t have.
For example, if we want to see all of the float object’s attributes and methods, we can use the following code: dir(float)
. It returns a list of all the attributes and methods of the floating object.
To avoid the AttributeError, check if attribute ‘#’ exists in dir(float)
using the in operator. As an example:
number = 9.9 # Check whether the append attribute exists in float. if 'append' in dir(float): number.append('9') print(number) else: print("There is something wrong here. The floating object has no this attribute!")
Output:
There is something wrong here. The floating object has no this attribute!
Summary
We have shown you three simple ways to avoid the AttributeError: ‘float’ object has no attribute ‘#’ in Python. If you see this error again, make sure it isn’t due to a spelling error. If there are no typos, try one of the three debugging methods listed above.
Have a nice day!
Maybe you are interested:
- AttributeError: ‘list’ object has no attribute ‘join’
- AttributeError: ‘dict’ object has no attribute ‘add’
- AttributeError module ‘pandas’ has no attribute ‘read_csv’
Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java