Search code examples
pandasdata-sciencedata-analysisexploratory-data-analysis

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


I got this error

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

Let be x an array of continuous numerical values between 0 and 10

dts1['NewCol'] = np.apply_along_axis(getbool,axis=0, arr=x)

Let be getbool a function which returns 1 if the numerical value is more than 5 and 0 otherwise

def getbool(x):
    if x > 5: 
        return 1
    else: 
        return 0

Solution

  • The syntax np.apply_along_axis(getbool,dts1,axis=0, arr=x) is wrong, as mentionned by @Derek. If i understood your question correctly, the following code should do what you want:

    import numpy as np
    
    def getbool(x):
        if x > 5: 
            return 1
        else: 
            return 0
        
    getbool = np.vectorize(getbool)
    array = np.array([1, 2, 3, 1, 2, 5, 7, 9, 2, 7])
    
    print(getbool(array))
    

    The output is: [0 0 0 0 0 0 1 1 0 1]