Home > Enterprise >  If with annidated conditions
If with annidated conditions

Time:09-23

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!

CodePudding user response:

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

CodePudding user response:

create a dict to map col1 to col2, then compare and update the col3

# dict of the mapping col1 to col2
d = {'A':'x','B':'p','C':'y'}

#map col1 using dict and compare with col2, if matches, makes it OK
df.loc[df['column2'].eq(
    df['column1'].map(d)), 'column3'] = 'OK'

# fillna values with 'KO'
df['column3'].fillna('KO', inplace=True)
df
column1     column2     column3
0   A   x   OK
1   A   z   KO
2   B   p   OK
3   C   y   OK
4   C   w   KO
  • Related