将 if-then 语句应用于多个列并输出到新列 - 熊猫



我正在尝试在多个列上应用 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_Correct"列表中 我的代码是:

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'的实例之间不支持'>'"。我怎样才能做到这一点?谢谢!

您可以将双numpy.where与构造函数一起使用DataFrame

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

它使用函数 numpy 符号,然后按dict replace

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

编辑:

如果得到:

">

str"和"int"实例之间不支持">">

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

df = df.astype(float)

或者还有另一个问题,一些不好的非数值。然后需要to_numeric ror 将此值替换为 NaN s,然后用一些标量替换它们,例如用 fillna 0

df = df.apply(pd.to_numeric, errors='coerce').fillna(0)

相关内容

最新更新