0

I'm trying to concatenate some conditions but it's getting quite hard to solve it, here's the problem:

I have a df with 3 columns:

| Column1 | Column2 | Column3 |
|:-------:|:-------:|:-------:|
| A       | x       |         |
| A       | z       |         |
| B       | p       |         |
| C       | y       |         |
| C       | w       |         |

So, what I'm trying to do is compare the value in column1 and column2 and if matches the condition add a "OK" to that row in column3 otherwise "KO" I'm trying something like this:

for letter in df['Column1']:
  for letter1 in df['Column2']:
    if((letter == 'A') and (letter1 == 'x')):
      df['Column3'].append('OK')
    if((letter == 'B') and (letter1 == 'p')):
      df['Column3'].append('OK')
    if((letter == 'C') and (letter1 == 'y')):
      df['Column3'].append('OK')
    else:
      de['Column3'].append('KO')

The output should be like this:

| Column1 | Column2 | Column3 |
|:-------:|:-------:|:-------:|
| A       | x       |     OK  |
| A       | z       |     KO  |
| B       | p       |     OK  |
| C       | y       |     OK  |
| C       | w       |     KO  |

Thanks for the help!

Enrique GE
  • 11
  • 2
  • 1
    Does this answer your question? [pandas create new column based on values from other columns / apply a function of multiple columns, row-wise](https://stackoverflow.com/questions/26886653/pandas-create-new-column-based-on-values-from-other-columns-apply-a-function-o) – matszwecja Sep 23 '22 at 12:21
  • 1
    I can't find "annidate" in an English dictionary, but it seems to be a word meaning "nested" in Italian ...? – tripleee Sep 23 '22 at 12:27

1 Answers1

0

If you create a second dataframe and join, you can avoid the many ifs:

import pandas as pd

df = pd.DataFrame({'column1': list('AABCC'), 
               'column2': list('xzpyw')})
# data frame with ok's
ok = pd.DataFrame({'column1': ['A', 'B', 'C'],
                   'column2': ['x', 'p', 'y'],
                   'column3': ['OK'] * 3})

df = df.merge(ok, on = ['column1', 'column2'], how = 'left')
df['column3'] = df['column3'].fillna('KO') # anything not in ok
r.user.05apr
  • 5,356
  • 3
  • 22
  • 39