Home > Back-end >  Check for bool in numpy array python
Check for bool in numpy array python

Time:06-18

i got a little problem. I want to check every element of a numpy array of dtype 'Array of object', if there are any values==NaN. The col of Name is not supposed to be checked If the value is NaN then the function sets this value to zero. I get an an error:

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

This is my array:

Name    Watt    Fluenz  
A1C1    10  nan
A1C2    20  nan
A1C3    30  nan

This is my function:

def check_NaN(arr):
    [row, col] = arr.shape
    for i in range(col):
        if arr[i] == 'Name':
            continue
        elif arr[i] == 'name':
            continue
        else:
            for j in range(row):    
                if arr[i][j].isnan():
                    arr[i][j] = 0

How can I solve this problem?

CodePudding user response:

Seems like you need pandas, as you are working with 2-d data.

import pandas as pd
df = pd.DataFrame(arr)

Then, you can easily check

>>> df['Fluenz'].isnull()

and it will return an iterable of Trues and Falses.

CodePudding user response:

def check_NaN(arr):
    [row, col] = arr.shape
    for i in range(col):
        if arr[0][i] == 'Name':
            continue
        elif arr[0][i] == 'name':
            continue
        else:
            for j in range(1,row):
                if arr[j][i].dtype == object and np.isnan(arr[j][i]):
                    arr[j][i] = 0

Mistakes:

  1. Comparison of whole 1D array with string "Name"/"name"
  2. Accessing indexes out of bound by using arr[i][j] instead of arr[j][i]
  3. "If" condition for checking is "nan" was incorrect.

Cheers

  • Related