'Fixing truth value error in pandas dataframe

I have a pandas dataframe df. I'm trying to create a new column 'Activity' and give it a string variable based on condition.

I'm getting

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I checked several places it mentions that I should have comparison operator as & vs 'and'. But even that does not work.

if ((df['%Deliverble'] > df['Deliverble_mean']) & (df['Action'] > df['Action_mean'])):
    df['Activity']='Jackpot'
elif ((df['%Deliverble'] > df['Deliverble_mean']) & (df['Action'] < df['Action_mean'])):
    df['Activity'] = 'Accumalation'
elif ((df['%Deliverble'] < df['Deliverble_mean']) & (df['Action'] > df['Action_mean'])):
    df['Activity'] = 'Action'
elif ((df['%Deliverble'] < df['Deliverble_mean']) & (df['Action'] < df['Action_mean'])):
        df['Activity'] = 'No Interest'


Solution 1:[1]

You could use Pandas apply and pass the function you just described to be executed along the row axis (axis=1).

def generate_activity(x):
    if ((x['%Deliverble'] > x['Deliverble_mean']) & (x['Action'] > x['Action_mean'])):
        return 'Jackpot'
    elif ((x['%Deliverble'] > x['Deliverble_mean']) & (x['Action'] < x['Action_mean'])):
        return 'Accumalation'
    elif ((x['%Deliverble'] < x['Deliverble_mean']) & (x['Action'] > x['Action_mean'])):
        return 'Action'
    elif ((x['%Deliverble'] < x['Deliverble_mean']) & (x['Action'] < x['Action_mean'])):
        return 'No Interest'
    return ''

df['Activity'] = df.apply(generate_activity, axis=1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 n1colas.m