AttributeError- 'numpy.ndarray' object has no attribute 'index' - python

I keep getting this error message:
newmaxleft=cl1count.index(max(cl1count))
AttributeError: 'numpy.ndarray' object has no attribute 'index'
The purpose of the code is to find the first occurrents of the column with the largest amount of white pixels.
My Code:
cl = cl[top:bottom, left:right]
cl1mask = np.uint8(np.where(cl == 0, 0, 1))
cl1count = cv2.reduce(cl1mask, 0, cv2.REDUCE_SUM, dtype=cv2.CV_32SC1)
cl1count.flatten().tolist()
newmaxleft=cl1count.index(max(cl1count))

Numpy doesn't have index method. It uses where (for general purposes) or some specific functions. In your case the best choice is
newmaxleft = cl1count.argmax()
You can also use
newmaxleft = np.where(a==max(a))[0][0]
But it's less efficient. First [0] returns np.array of positions, second [0] returns first occurrence.

The error happens because numpy arrays don't have the index attribute, as the error says. So instead of using index, use something like newmaxleft=np.where(cl1count == max(cl1count)) where you can use newmaxleft[0] to get the first occurrence. You could also use argmax.

Related

Unable to use mean funcation on list of integers - AttributeError: 'list' object has no attribute 'mean'

I am learning Python and have been trying out some simple equations using NumPy. While trying to calculate the mean of a list of numbers using the mean() function, I encountered an error.
AttributeError: 'list' object has no attribute 'mean'
P.S To avoid any doubt, Numpy has been installed via pip and works fine. In addition, the two list objects are intentionally different shapes.
Here is my script/code:
import numpy as np
family_name = ['Homer','Marge','Maggie']
family_age = [39,36,2,8]
family_name_age = np.array([family_name, family_age], dtype=object)
avg_family_age = family_name_age[1].mean()
print('Average age: {:.2f}'.format(avg_family_age))
When I run this in a jupyter notebook, I get the following error message.
AttributeError
Traceback (most recent call last) c:\Users\my_pc\a_folder\01-numpy-practice.ipynb
in <cell line: 5>()
2 family_age = [39,36,2,8]
3 family_name_age= np.array([family_name, family_age], dtype=object)
----> 4 avg_family_age = family_name_age[1].mean()
6 print('Average age: {:.2f}'.format(avg_family_age))
AttributeError: 'list' object has no attribute 'mean'
However, when I try mean() as follows it works fine:
family_height_cm = [183,172,82]
family_weight_kg = [109,60,11]
family_bmi_data = np.array([family_height_cm,family_weight_kg])
avg_fam_height = family_bmi_data[0].mean()
print('Average height: {:.2f}'.format(avg_fam_height))
It works perfectly and I get a figure of Average height: 145.67
It would be very helpful if someone could give me some insight into what I'm doing wrong and an explanation of the theory that is as simple as possible. Mega thank you in advance.
In the first example, you are specifying the dtype as object. This will leave you with an array of two python lists. You cannot call .mean() on a python list.
family_name_age[1] is a list, but family_bmi_data[0] is a NumPy array. Unlike a NumPy array, a list does not have a mean method.
#jprebys provided a clear reason why I encountered the error: "AttributeError: 'list' object has no attribute 'mean'"
In the first example, you are specifying the dtype as object. This
will leave you with an array of two python lists. You cannot call
.mean() on a python list - #jprebys https://stackoverflow.com/a/74116157/1753769
While #learner provided a code snippet that enabled me to achieve the result I was aiming for.
By first setting my variable: family_age as a NumPy array: family_age = np.array([39,36,2,8]). I was able to use the mean method/function as needed.
So my full code block as provided by #learner looked like this:
family_name = ['Homer','Marge','Maggie']
family_age = np.array([39,36,2,8])
family_name_age= np.array([family_name, family_age], dtype=object)
avg_family_age = family_name_age[1].mean()
print('Average age: {:.2f}'.format(avg_family_age))
Thank you #learner and #jprebys

Pandas: AttributeError: 'str' object has no attribute 'isnull'

I'm creating a new column named lead_actor_actress_known whose values is boolean based on whether there value in 2nd column lead_actor_actress has value or not. If there is a value(Name of actors) populate 1st column using True if there is no value, return False
AttributeError: 'str' object has no attribute 'isnull'
My code is throwing an error above.
df['lead_actor_actress_known'] = df['lead_actor_actress'].apply(lambda x: True if x.isnull() else False)
What i'm i missing?
Henry Ecker's comment contains the answer to this question, I am reproducing in the answer section for convenience. Replace your application of the .apply() method with the code df['lead_actor_actress_known'] = df['lead_actor_actress'].isna().
The thing to know here is that df['lead_actor_actress'].isna() returns a "Boolean mask" (a series of True and False values) and this is exactly what you are asking to assign the variable lead_actor_actress.

appending to list within list gives AttributeError: 'int' object has no attribute 'append'

when executing the following code, I get the error message "AttributeError: 'int' object has no attribute 'append'". I know this error occurs when I try to append to an integer, for example, which is not the case here since I checked that via type(section[len(section)-1]) which returned list
def increasing_section(a_list):
section = [[a_list[0]]]
i = 1
while i < len(a_list):
if a_list[i-1] < a_list[i]:
section[len(section)-1].append(a_list[i])
else:
section.append(a_list[i])
i += 1
return section
The error comes from this line:
section[len(section)-1].append(a_list[i])
because at some point, when your if condition will not be met, the following line:
section.append(a_list[i])
will add an integer in section and the first line will produce error as section[len(section)-1] will be an integer
I'm not sure what exactly you are trying to do, but to fix this you need to change section[len(section)-1].append(a_list[i]). Because section[len(section)-1] will return an integer and integer doesn't have append method, so if you want to insert an element to a list at a particular index, try section.insert(index, value)

Using len() with if/else to populate dataframe variable

I am looking to add a variable to my dataframe that concatenates several other variables. I know that if variable 'do' is less that 4 characters, it is garbage input and I should instead use variable 'ra'. However, the below throws an attribute error: "AttributeError: ("'str' object has no attribute 'len'", 'occurred at index 0')". Is the apply operation the correct way to go about what I'm doing, and if so, how can I correct my function?
def get_combined(row):
if row['do'].len() < 4:
return row['ra']+' '+row['mi']+' '+row['fa']+' '+row['so']
else:
return row['do']+' '+row['mi']+' '+row['fa']+' '+row['so']
df['Combined'] = df.apply(get_combined, axis=1)
The second line should be:
if len(row['do']) < 4:

'NoneType' object has no attribute '__getitem__' 4

from collections import deque
def muladd(f1,f2_inv):
global ans
for j in f1:
ans = f1[j]*f2_inv[j]
f1 = [2,3,7,5,4,0,0,0,0,0,0,0,0]
f2 = [0,0,0,0,8,7,6,5,9,0,0,0,0]
conv = [0,0,0,0,0,0,0,0,0]
f2_inv = f2.reverse()
for i in conv:
conv[i]= muladd(f1,f2_inv)
print conv[i]
f1.rotate(1)
​
I am not able to run the code.
When I run this code I get the error:
'NoneType' object has no attribute '__getitem__'
reverse(), like many methods that operate on lists, does not return anything, but modifies the list in-place. So f2 is None. You should use the standalone reversed() function.
f2_inv = list(reversed(f1))
or slicing:
f2_inv = f1[::-1]
(Note, there are other issues with this code, such as the fact that i is always 0 in your loop because you iterate over a list of only 0s.)
In your loop
for i in conv:
conv[i]= muladd(f1,f2_inv)
print conv[i]
f1.rotate(1)
i will be an object (it loops over all the objects of conv, so i is an object instead of an index number). This way you cannot use conv[i]. To be able to use i as an index, use:
for i in range(len(conv)):
conv[i]= muladd(f1,f2_inv)
print conv[i]
f1.rotate(1)
(this is not the cause of your error, but will cause problems if yours is fixed, as conv[i] would always be conv[0], because i is 0 instead of the current index number)

Categories

Resources