Python 将if-then语句应用于多个列,并输出到新的列

Python 将if-then语句应用于多个列,并输出到新的列,python,pandas,Python,Pandas,我试图在多个列上应用if-then语句,然后将if-then语句的结果输出到新的列。我的数据如下所示: AtoB BtoC CtoD 240 600 1000 -30 540 540 50 -50 0 0 0 -10 我期望的输出是: AtoB_C BtoC_C CtoD_C C C C

我试图在多个列上应用if-then语句,然后将if-then语句的结果输出到新的列。我的数据如下所示:

    AtoB    BtoC    CtoD      
     240     600    1000
     -30     540     540
      50     -50       0
       0       0     -10
我期望的输出是:

    AtoB_C  BtoC_C  CtoD_C
         C       C       C
         E       C       C
         C       E       S
         S       S       E
其思想是if-then语句的结果存储在这些新变量中,原始变量仍然存在。要评估的变量在“结果”列表中,输出变量(目前没有任何内容)在“结果正确”列表中。我的代码是:

Result = ['AtoB','BtoC','CtoD'] 
Result_Correct = ['AtoB_C','BtoC_C','CtoD_C']
    for row in DF[Result]:
        if row > 0:
            [Result_Correct].append('c')
        elif row == 0:
            [Result_Correct].append('s')
        else:
            [Result_Correct].append('e')
    DF[Result_Correct] = [Result_Correct]
当我尝试运行此命令时,会收到消息“'>”在'str'和'int'实例之间不受支持。我怎样才能做到这一点?谢谢

您可以将double与
数据帧
构造函数一起使用:

Result = ['AtoB','BtoC','CtoD'] 
#new column names
Result_Correct = ['AtoB_C','BtoC_C','CtoD_C']
#filter coumns by  list Result if necessary
df = df[Result]

df = pd.DataFrame(np.where(df>0, 'C',
                  np.where(df==0, 'S', 'E')), index=df.index, columns=Result_Correct)
print (df)
  AtoB_C BtoC_C CtoD_C
0      C      C      C
1      E      C      C
2      C      E      S
3      S      S      E
另一个解决方案:

Result = ['AtoB','BtoC','CtoD'] 
Result_Correct = ['AtoB_C','BtoC_C','CtoD_C']
df = df[Result]

d = {1:'C', 0:'S', -1:'E'}
df = pd.DataFrame(np.sign(df.values), index=df.index, columns=Result_Correct).replace(d)
print (df)
  AtoB_C BtoC_C CtoD_C
0      C      C      C
1      E      C      C
2      C      E      S
3      S      S      E
它使用函数,然后通过
dict

print (np.sign(df.values))
[[ 1  1  1]
 [-1  1  1]
 [ 1 -1  0]
 [ 0  0 -1]]
编辑:

如果获得:

在'str'和'int'的实例之间不支持'>'

这意味着某些int值是字符串,然后使用:

df = df.astype(float)
或者还有另一个问题,一些糟糕的非数值。然后需要ror将这些值替换为
NaN
s,然后用一些标量替换它们,如
0


这正是我想做的,非常有帮助。感谢您添加有关错误的部分。谢谢
df = df.apply(pd.to_numeric, errors='coerce').fillna(0)