Home > Back-end >  Checking a cell in pandas for 0, with different types of cell content
Checking a cell in pandas for 0, with different types of cell content

Time:02-10

I'm trying to do an if where I check whether a cell is 0, the problem is that sometimes the cell will have a float, an array or just a 0.

I've done

if df.iat[i,df.columns.get_loc('B')] == 0:
     print('something')

that gives me an error when there is an array:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

To try and solve that I tried:

if df.iat[i,df.columns.get_loc('B')].all() == 0:
     print('something')

which arises the error

AttributeError: 'float' object has no attribute 'all'*, when the content of the cell is a float

Any ideas how can I work around this issue?

CodePudding user response:

Because column "B" contains values of different types, you'll need to check for data type first before evaluating if the value is equal to some value. So for example, if df.iat[i,df.columns.get_loc('B')] is equal to [1,2], then

df.iat[i,df.columns.get_loc('B')] == 0

is equivalent to [1,2] == 0 which doesn't make sense.

You can check the data type first before checking if it's equal to 0 or not.

x = df.iat[i,df.columns.get_loc('B')]
if isinstance(x, (int,float)) and x == 0:
    # do something
else:
    # do something else

Also, if you want to do the same check on the entire column (assuming you want to create a boolean list), you can use a list comprehension where you do a check the data type as well as if it's equal to 0 or not:

out = [True if isinstance(x, (int,float)) and x==0 else False for x in df['B']]

You can assign it to a column as well:

df['zeros'] = out
  • Related