我在使用pandas处理一个DataFrame,并需要根据一些条件添加一个新列。
我的DataFrame是这样的:
discount tax total subtotal productid
3 0 20 13 002
10 3 106 94 003
46.49 6 21 20 004
我需要在添加一个名为Class的新列时应用一些条件。
条件如下:如果discount > 20 & total > 100 & tax == 0
,那么Class应为1,否则应为0
我尝试的方法如下:
def conditions(s):
if (s['discount'] > 20) and (s['tax'] == 0) and (s['total'] > 100):
return 1
else:
return 0
df_full['Class'] = df_full.apply(conditions, axis=1)
但它返回了一个错误:
TypeError: (“‘>’ not supported between instances of ‘str’ and ‘int'”, ‘occurred at index 18’)
我该如何解决这个问题呢?
请帮帮我!
提前谢谢!
回答:
我建议创建一个布尔掩码并转换为int
类型,True
值转换为1
,False
值转换为0
,同时将and
更改为&
以进行位运算的AND
操作:
print (df_full)
discount tax total subtotal productid
0 3.00 0 20 13 002
1 40.00 0 106 94 003
2 46.49 6 21 20 004
你还可以检查所有非数值:
print(df_full[pd.to_numeric(df_full['discount'], errors='coerce').isnull()])
# 转换为数值 - 非数值将转换为`NaN`
df_full['discount'] = pd.to_numeric(df_full['discount'], errors='coerce')
df_full['Class'] = ((df_full['discount'] > 20) &
(df_full['tax'] == 0) &
(df_full['total'] > 100)).astype(int)
print (df_full)
discount tax total subtotal productid Class
0 3.00 0 20 13 002 0
1 40.00 0 106 94 003 1
2 46.49 6 21 20 004 0