1

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.

excelguy
  • 1,574
  • 6
  • 33
  • 67

1 Answers1

5

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.

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
  • Why do you mention the joinkey again after the last comma? – excelguy Nov 27 '19 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. – Celius Stingher Nov 27 '19 at 15:06