Attribute error even after adding the enumerate - python

I keep getting Attributeerror such as 'tuple' object has no attribute 'split'.
At first I did not have enumerate in this code, and I got attribute error saying that 'int' object has no attribute 'split'. So added te enumerate referencing this question.
But i sill get the same error.
enterreleased_date = []
released_country = []
released_year = []
for i in enumerate(df['released']):
date = i.split("(")[0]
country = i.split("(")[1].replace(')','')
released_date.append(date)
released_country.append(country)
df['released_country'] = released_country
df['released_date'] = released_date
df['released_date'] = pd.to_datetime(df['released_date'])
df['released_year'] = df['released_date'].dt.year
df['released_month'] = df['released_date'].dt.month
#drop the unneccessary columns --yearcorrect was created by accident so we'll delete that as well
df.drop(['year','released','released_date','yearcorrect'], axis=1, inplace=True)
df['logbudget'] = np.log(df['budget'])
df['loggross'] = np.log(df['gross'])
df.head(3) code here

When you are calling this:
for i in enumerate(df['released']):
enumerate(x) return a tuple object of 2 elements. 1st the number i of sample in x and 2nd the i-th element in x itself. What do you get as i then is a tuple of the two elements per iteration. If you are using .split for a string, you need to write:
for i, string in enumerate(df['released']):
So now you get the two elements inside the tuple of each iteration. And then you can use split() as: string.split().
Try:
for i in enumerate(df['released']):
print(i)
And:
for i, string in enumerate(df['released']):
print(i)
print(string )
To see the difference.
EDITED: As #flakes suggests, it seems like you don't actually need to use enumerate. As for-loops in python are wiser than other languages and they iterate over elements in arrays/lists/etc and don't need a number to help them. for elem in df['released']: would be enough.

Related

Comparing an item in a list to an integer gives TypeError Python

I have an array in my python program called ageArray. It contains the same attribute from each object in a group. Here's the intitialisation code:
ageArray = [[amoeba.age] for amoeba in amoebas]
Because the I want the attribute to change, I intitialise it at the start of a while statement. After this I have the following two lines of code:
for amoeba in amoebas:
amoeba.age = amoeba.age + 1
This is intended to add 1 to each age attribute, which will then be copied over to the ageArray the next time the while loop is iterated.
The use for this array is to add an extra requirement when two of the amoeba(objects) collide, as well as checking their x and y coords, I use this:
if ageArray[i] >= 10 and ageArray[h] <= 10:
This code is intended to make sure that the ages of the amoebae are more than 10 (the reason for this is complex and so I won't explain). For some reason this piece of code is throwing up this error:
TypeError: '>' not supported between instances of 'list' and 'int'.
Furthermore, is my code for adding 1 to each amoeba.age attribute correct? Tried using lambda with agearray but couldn't get it to work.
You create a list with List Comprehensions, where each element is a list with one element ([amoeba.age] is a list with a single element):
ageArray = [[amoeba.age] for amoeba in amoebas]
Just leave out the inner square brackets to create a list:
ageArray = [amoeba.age for amoeba in amoebas]
Initialise your list like this:
ageArray = [amoeba.age for amoeba in amoebas]
The way you are initialising is, creating a list of lists, that's why it is giving that type error.

Access list from a function

I have created a function which returns a list
def GetAddressContainer(obj,obj1):
mylist = list()
for i in test['adresss']:
addresscotainer = i[id]
return mylist(addresscontainer)
When i call the function -
UkContainer = GetAddressContainer(Postcode,Country)
i get the following error message:
TypeError: 'list' object is not callable in python
Any ideas why i am getting this error and what i would have to update?
The problems seem to be in
return mylist(addresscontainer)
You using parentheses on the list and therefore calling it as a function, that's why you get the error. Without any more code I not entirely sure what to replace it with though.
Issues
The line mylist = list() basically creates an empty list which you can use to store any values. In the code mylist is being called (using (...)) which does not make sense in python since mylist is not a function.
Another issue with the code is that the value of addresscontainer is never being inserted into mylist.
Possible Solutions
So, as per your problem, either of the following solutions can be used:
Append addresscontainer into mylist iteratively within the for loop:
for i in test['adress']:
addresscontainer = i[id]
mylist.append(addresscontainer) # Inserts the value at the end of list
return mylist # Returns the list
[RECOMMENDED] Use list comprehension:
def GetAddressContainer(...):
return [i[id] for i in test['adress']] # Build list using "List Comprehension"
Replace mylist(addresscontainer) with list(addresscontainer) code.
Only list word could be a callable function because it defines a class of any list. And mylist = list() will be an instance of an abstract list, then, not callable.
change mylist = list() to mylist = []
it will create an empty list instead of a list object.
and you are not appending anything to the list.

Adding Booleans to a list results in a TypeError

I've created a blank list and am attempting to add a boolean to that list. However, I'm getting a few different errors. I'm fairly new to Python so any explanations would be helpful.
What I'm attempting to do is:
new_list=[]
new_list[0] = True #ERROR: TypeError: 'type' object does not support item assignment
or
new_list=[]
new_list.append(True) #ERROR: TypeError: descriptor 'append' requires a 'list' object but received a 'bool'
More precisely, I'm attempting to send this through a loop
new_list=[]
for arg in args:
if (arg == 'foo' or arg == 'bar'):
new_list[arg] = True
Obviously, the error in the first block is because the list is not accepting the boolean that's being passed. The second is also providing a similar error. However, because this is a blank list, shouldn't this accept any input?
I've attempted to follow this however, it looks like even this may not work.
Thanks in advance.
new_list = [] creates an empty list. In your first try, you are trying to access new_list[0], but the first place in the list ([0]) does not exist, because the list is empty.
When you want to add values to the list you need to use append. So your second try is correct, you should use: new_list.append(True), but the first line where you define the empty list is wrong. You used new_list[] instead of new_list = [].
As for the usage of new_list[], it's a syntax error. If you want to define an empty list you should use new_list = [] or new_list = list().
If you want to track the name of the arg if it is either "bar" or "foo", you could try something like this:
list = []
for arg in args:
if arg == 'foo' or arg == 'bar':
argDic = { arg: True }
list.append(argDic)
print(list)
# [{'foo': True}, {'bar': True}]
new_list = [] #creates a new list
new_bool_list = [True]*10 # creates a list size 10 of booleans
In python you don't have to set the size of the list, you can create an empty list and add onto it.
new_list = []
new_list.append(True)
print(new_list)
--------------
output:
[True]
for your loop question it depends on your arguments. new_list[arg] = True is generally how you set a value in a dictionary (HashMap in other languages). I think you'd be better off researching those for your intended question.

.index() generates AttributeError: 'dict_values' object has no attribute 'index'

I'm trying to rewrite this Python2 code to Python3 accepted syntax. The .index() methods generates the following error:
AttributeError: 'dict_values' object has no attribute 'index'
This is because .index() is no valid syntax in Python3. I've read that a list should be used to work around the problem, but I can't figure out how to do it. Anyone any idea how to work around the problem?
words1 = [self._word_to_id.keys()[self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1)]
indices = [i for i, w in enumerate(words1) if w in PUNCTUATIONS]
for i in indices:
words1[i], words1[i-1] = words1[i-1], words1[i]
words2 = [self._word_to_id.keys([self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1, len(data_x))]
all_words = words1 + [puncts[-1]] + words2
content = ' '.join(all_words)
min_step = len(puncts)
You are calling self._word_to_id.values() which returns the class dict_values and not list. dict_values does not inherit from list and does not have the index method because of that.
You need to convert your dictionary values into a list to use the index function. Try this:
list(self._word_to_id.values()).index(data_x[index])
words1 = [list(self._word_to_id.keys())[list(self._word_to_id.values()).index(data_x[index])] for index in range(len(puncts) - 1)]

Create a list of defaultdict in python

I am doing the following :
recordList=[lambda:defaultdict(str)]
record=defaultdict(str)
record['value']='value1'
record['value2']='value2'
recordList.append(record)
for record in recordList:
params = (record['value'],record['value2'],'31')
i am getting the error :
TypeError: 'function' object is not
subscriptable
what is wrong here ?
recordList=[lambda:defaultdict(str)]
creates a list with a function that returns defaultdict(str). So it's basically equivalent to:
def xy ():
return defaultdict(str)
recordList = []
recordList.append( xy )
As such, when you start your for loop, you get the first element from the list, which is not a list (as all the other elements you push to it), but a function. And a function does not have a index access methods (the ['value'] things).
recordList is a list with 1 element which is a function.
If you replace the first line with
recordList = []
the rest will wor.
you're adding a lambda to recordList, which is of type 'function'. in the for .. loop, you're trying to subscript it (record['value'], record['value2'], etc)
Initialize recordList to an empty list ([]) and it will work.

Categories