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

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:

Related

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

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.

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)

'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)

Trouble creating new variable based off of existing variable

I am trying to create a new variable based off of an existing variable in my df. I have run into this error before and I would like to know what I am doing wrong.
Code:
def DEMO2(a):
if a['DEMO']=='02-05C':
return 'P 02-11'
elif a['DEMO']=='65+M':
return 'P 55-99'
merge_df['DEMO2']=merge_df.apply('DEMO2', axis=1)
TypeError: ("'str' object is not callable", 'occurred at index 0')
I feel like there is an obvious answer that I am missing...
You do not need the DEMO2 function even .
merge_df['DEMO2']=merge_df.DEMO.replace({'02-05C':'P 02-11','65+M':'P 55-99'})
Well you're getting that error because of this
merge_df['DEMO2']=merge_df.apply('DEMO2', axis=1)
Should (probably) be this:
merge_df['DEMO2']=merge_df.apply(DEMO2, axis=1)

"object of type 'NoneType' has no len()" error

I'm seeing weird behavior on this code:
images = dict(cover=[],second_row=[],additional_rows=[])
for pic in pictures:
if len(images['cover']) == 0:
images['cover'] = pic.path_thumb_l
elif len(images['second_row']) < 3:
images['second_row'].append(pic.path_thumb_m)
else:
images['additional_rows'].append(pic.path_thumb_s)
My web2py app gives me this error:
if len(images['cover']) == 0:
TypeError: object of type 'NoneType' has no len()
I can't figure out what's wrong in this. Maybe some scope issue?
You assign something new to images['cover']:
images['cover'] = pic.path_thumb_l
where pic.path_thumb_l is None at some point in your code.
You probably meant to append instead:
images['cover'].append(pic.path_thumb_l)
your problem is that
if len(images['cover']) == 0:
checks the LENGTH of the value of images['cover'] what you meant to do is check if it HAS a value.
do this instead:
if not images['cover']:
The first time you assign: images['cover'] = pic.path_thumb_l, it replaces the value of the empty list initially stored in images['cover'] with the value of pic.path_thumb_l which is None.
Maybe your code in this line must be images['cover'].append(pic.path_thumb_l)
We can also see the type in the same condition, to avoid something if you want, like
if myArray is None:
#Do something when array has no len()
else:
#Do something when array has elements and has len()
In my case I was looking for something in the array, but only if has something, when id does not, was None the type and I need to create it. Hope this works for someones.

Categories

Resources