我正在尝试对多个列应用 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 sign然后 replace通过 dict:
print (np.sign(df.values))
[[ 1 1 1]
[-1 1 1]
[ 1 -1 0]
[ 0 0 -1]]
编辑:
如果得到:
'>' not supported between instances of 'str' and 'int'
这意味着一些 int 值是字符串,然后使用:
df = df.astype(float)
或者还有另外一个问题,一些不好的非数值。然后需要to_numeric或者将此值替换为 NaN,然后用一些标量替换它们,例如 0 和 fillna :
df = df.apply(pd.to_numeric, errors='coerce').fillna(0)
