Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧上的Panadas条件返回TypeError:'&燃气轮机';在';str';和';int';_Python_Pandas_Machine Learning_Pandas Apply - Fatal编程技术网

Python 数据帧上的Panadas条件返回TypeError:'&燃气轮机';在';str';和';int';

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的新列时,我需要应用一些条件 条件如下: 如果

我正在使用pandas处理一个数据帧,我需要根据一些条件添加一个新列

我的数据帧是:

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