-1

I have tried looping into a column, there are three different values which should be filled in the columns but only one value is getting filled.

for i in df_j['token']:
    if i in ["AK","BK","BW","AC","AK","AR","BA"]:
        df_j['check']='1_Check'
    elif i in ["AW","AA"]:
        df_j['check']='STP'
    elif i in ["MD","MW","MK","NW","NK","ND","PW","PK"]:
        df_j['check']='Normal'

Above is the code and value which is coming is "normal' in all rows.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Abhay kumar
  • 203
  • 1
  • 4
  • 13
  • Welcome to Stack Overflow! Would you be able to flesh out your question a little more to help us understand what you need? What output are you getting and what output are you expecting? Could you have a look at the code that you've posted and check that it's correct, as your indentation is definitely off. Check out ["How to ask"](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) for more tips. Thanks! – Ari Cooper-Davis Mar 09 '18 at 10:21
  • what is df_j['check'] in your dataframe? you should be replacing the values one by one. – Sumit S Chawla Mar 09 '18 at 10:31
  • df_j['check'] is the new column which I am creating with the help of this loop. – Abhay kumar Mar 09 '18 at 11:13
  • Possible duplicate of [Creating a new column based on if-elif-else condition](https://stackoverflow.com/questions/21702342/creating-a-new-column-based-on-if-elif-else-condition) – Patrick Artner Mar 09 '18 at 11:33

1 Answers1

0

You could search SO, find Creating a new column based on if-elif-else condition and apply Zelazny7's answer to your situation.

This is a Minimal, Complete, and Verifiable example for a solution: copy&paste = works

import pandas as pd

def f(row):
  if row['token'] in ["AK","BK","BW","AC","AK","AR","BA"]:
      return '1_check'
  elif row['token'] in ["AW","AA"]:
      return 'STP'
  elif row['token'] in ["MD","MW","MK","NW","NK","ND","PW","PK"]:
      return 'Normal'

  return None # explicit return None as default for unmapped values


df = pd.DataFrame(["AK","BK","BA","AW","NOTHIGN","MD","ND","PASS"],None,['token'])

df['check'] = df.apply(f, axis=1)

print(df) 

Output:

     token    check
0       AK  1_check
1       BK  1_check
2       BA  1_check
3       AW      STP
4  NOTHIGN     None
5       MD   Normal
6       ND   Normal
7     PASS     None
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • @Abhaykumar [how-does-accepting-an-answer-work](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Patrick Artner Mar 09 '18 at 12:18