Pandas DataFrame条件返回TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

我在使用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值转换为1False值转换为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

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注