2

I want to do: IF a column contains values , then apply a change to joinkey column, IF a column contains different values, then apply a different change to joinkey column, etc.

IF df.loc[df['product'].isin('value1','value2') THEN df['joinkey'] = df['joinkey'] + variable1

then repeat

IF df.loc[df['product'].isin('value3','value4') THEN df['joinkey'] = df['joinkey'] + variable2

Hopefully this makes sense, any help would be appreciated.

Thanks.

1
  • 1
    why not try to use np.where ? this should do it
    – user96564
    Commented Nov 27, 2019 at 14:49

1 Answer 1

7

You could try and use np.where() for the column, maybe it will requiere more than one line of code.

import pandas as pd
import numpy as np
df['joinkey'] = np.where(df['product'].isin(['value1','value2']),df['joinkey']+variable1,df['joinkey'])
df['joinkey'] = np.where(df['product'].isin(['value3','value4']),df['joinkey']+variable2,df['joinkey'])

I've setted the false condition to be equal to the original value of joinkey but of course you can change that to fit your needs best.

2
  • Why do you mention the joinkey again after the last comma?
    – excelguy
    Commented Nov 27, 2019 at 15:03
  • Simply because of setting the false condition to the original value of joinkey but providing the flexibility for the user to change it to whatever he/she wants. I assume this, since it is not given. Also from numpy's documentation, either both or none of x and y should be given, therefore I can't leave it blank. Commented Nov 27, 2019 at 15:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.