首页 > 解决方案 > 数据框python中的操作

问题描述

对不起我的英语不好。

我有个问题。我有这个数据框,我想计算我的数据框中的利润结果:如果销售额 - (Couts_fixe + Couts_Variables) >=0 : 公司税 = (Sellings - (Couts_fixe + Couts_Variables))*其他税收:公司税 = 0

我认为它是这样的,但那是行不通的。

我有写这个:

if (df['Sellings']-df['Couts_Tot']) >=0:
 df['Taxes_Soc'] = (df['Sellings'] - df['Couts_Fixes'] - df['Couts_Variables'])*df['Taxes'] 
else : df['Taxes_Soc'] = 0

他们回答:“系列的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

如您所见,我们有每月的销售和成本和税金

谢谢你的帮助。

标签: pythonpandasnumpydataframe

解决方案


您收到错误The truth value of a Series is ambiguous是因为您在语句中使用了 a pd.Seriesof 布尔值。ifif语句需要一个布尔值,因此它不知道如何处理其中的一系列。

您正在寻找的是使用布尔掩码(一系列布尔值)进行索引。您可以创建掩码,然后根据掩码的值修改行。掩码的每一行都有一个 True 或 False 值。

该语法~mask获取掩码的布尔值not,因此它将 Trues 切换为 false,并将 false 切换为 True。

mask = (df['Sellings'] - df['Couts_Tot']) >= 0

df.loc[mask, 'Taxes_Soc'] = (
        (df.loc[mask, 'Sellings'] 
        - df.loc[mask, 'Couts_Fixes'] 
        - df.loc[mask, 'Couts_Variables'])
    * df.loc[mask, 'Taxes'])
df.loc[~mask, 'Taxes_Soc'] = 0

推荐阅读