Python 数据帧上的Panadas条件返回TypeError:'&燃气轮机';在';str';和';int';
我正在使用pandas处理一个数据帧,我需要根据一些条件添加一个新列 我的数据帧是:Python 数据帧上的Panadas条件返回TypeError:'&燃气轮机';在';str';和';int';,python,pandas,machine-learning,pandas-apply,Python,Pandas,Machine Learning,Pandas Apply,我正在使用pandas处理一个数据帧,我需要根据一些条件添加一个新列 我的数据帧是: discount tax total subtotal productid 3 0 20 13 002 10 3 106 94 003 46.49 6 21 20 004 在向数据帧添加名为Class的新列时,我需要应用一些条件 条件如下: 如果
discount tax total subtotal productid
3 0 20 13 002
10 3 106 94 003
46.49 6 21 20 004
在向数据帧添加名为Class的新列时,我需要应用一些条件
条件如下:
如果折扣>20&总额>100&税收==0
则等级应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:('str'和'int'的实例之间不支持'>',在索引18'处发生)
我如何解决这个问题
请帮帮我
提前谢谢 我建议创建布尔掩码并强制转换为
int
,True
s为1
s和False
s为0
s,也将和更改为和按位和
:
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()]
#for convert to numeric - non numeric are convert to `NaN`s
df_full['discount'] = pd.to_numeric(df_full['discount'], errors='coerce')
您好@jezreal,现在它返回另一个错误作为TypeError:“>”在'str'和'int'实例之间不受支持
我认为需要df_full['discount']=df_full['discount']=df_full['discount'].astype(float)
之前。ValueError:无法解析位置18处的字符串“discount>20”
@AbdulRehman-似乎有些非数值,一种可能的解决方案是df_full['discount']=pd.to_numeric(df_full['discount'],errors='concurve')
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