Python循环输出

时间:2018-03-09 10:06:24

标签: python python-3.x pandas

我已经尝试循环到一个列,有三个不同的值应该在列中填充但只有一个值被填充。

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'

以上是代码和价值即将来临"正常'在所有行中。

1 个答案:

答案 0 :(得分:0)

您可以搜索SO,找到Creating a new column based on if-elif-else condition并将Zelazny7's answer应用于您的情况。

这是解决方案的Minimal, Complete, and Verifiable example: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) 

输出:

     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