Search code examples
pythonpandasnumpyvalueerrorambiguous

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


So I know there is a ton of answers online about this error but I can not find one that pertains to numpy finding a value were something equals something in an array, or I am just to dumb to understand what they are saying. So here is my code:

import pandas as pd
import numpy as np
arr_1 = np.array([7, 1, 6, 9, 2, 4])
arr_2 = np.array([5, 8, 9, 10, 2, 3])
arr_3 = np.array([1, 9, 3, 4, 5, 1])

dict_of_arrs = {
    'arr' : [arr_1, arr_2, arr_3]
}
df = pd.DataFrame(dict_of_arrs)
filt = df.arr.apply(lambda x: np.diff(x)>0)
if filt==True:
    pass

and as the title shows I am getting the error:

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

Thank you

EDIT: Say instead of pass I wanted to do something like:

import pandas as pd
import numpy as np
arr_1 = np.array([7, 1, 6, 9, 2, 4])
arr_2 = np.array([5, 8, 9, 10, 2, 3])
arr_3 = np.array([1, 9, 3, 4, 5, 1])

dict_of_arrs = {
    'arr' : [arr_1, arr_2, arr_3]
}
df = pd.DataFrame(dict_of_arrs)
true_list = []
false_list = []
filt = df.arr.apply(lambda x: np.diff(x)>0)
for i in filt:
    if filt==True:
        true_list.append(i)
    else:
        false_list.append(i)

Solution

  • Your second code example would work but it has a typo. Instead of comparing the element you try to compare the entire array.

    for i in filt:
        if filt==True:
            true_list.append(i)
        else:
            false_list.append(i)
    

    Should be:

    for i in filt:
        if i == True:
            true_list.append(i)
        else:
            false_list.append(i)