0

I have the following pandas dataframe:

import pandas as pd
import numpy as np

d = {'country' : ['us','uk','au','ca'],
     'influencer' : [3000,304,100,10],
     'platform' : [87,87,87,87]}

df = pd.DataFrame(d)

I am trying to add a new column 'influencer_updated' which is the conditional addition of 2 columns - influencer & platform based on different countries.

I have tried to solve the problem based on the below code snippet:

if df[(df['country'] == 'us')]:
    df['influencer_updated'] = df['influencer'] + df['platform'] * 0.5
elif df[(df['country'] == 'uk') & (df['country'] == 'au')]:
    df['influencer_updated'] = df['influencer'] + df['platform'] * 0.25
else:
    df['influencer_updated'] = df['influencer']

The error I am getting is:

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

Please help!!

  • You can''t use `if` with vectors. Use `np.where`/`np.select`. – mozway Apr 01 '23 at 19:40
  • someone closed this a second before I could poste the answer... copy the following to your IDE and it will work. Sorry for bad formatting (thanks to person who closed) def create_col(row): if row.country == "us": return row.influencer + row.platform * 0.5 elif row.country == "uk": return row.influencer + row.platform * 0.25 else: return row.influencer df["influencer_updated"] = df.apply(create_col, axis=1) Note that this applies your logic to every row (and you tried to apply it to columns) – Klops Apr 01 '23 at 19:41
  • @Klops you definitely shouldn't do this in pandas. `apply` is slow. Use a vectorial method like in the duplicate. – mozway Apr 01 '23 at 19:54
  • 1
    Another option: `factors = {'us': 0.5, 'uk': 0.25, 'au': 0.25} ; df['influencer_updated'] = df['influencer'].mul(df['country'].map(factors).fillna(1))` – mozway Apr 01 '23 at 20:02
  • thats a cool way to do it, however you made a small mistake: `df['influencer_updated'] = df["influencer"] + df['platform'].mul(df['country'].map(factors).fillna(0))` – Klops Apr 01 '23 at 20:14

0 Answers0