python - 数据框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()。 ”
谢谢你的帮助。
解决方案
您收到错误The truth value of a Series is ambiguous
是因为您在语句中使用了 a pd.Series
of 布尔值。if
该if
语句需要一个布尔值,因此它不知道如何处理其中的一系列。
您正在寻找的是使用布尔掩码(一系列布尔值)进行索引。您可以创建掩码,然后根据掩码的值修改行。掩码的每一行都有一个 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
推荐阅读
- javascript - 如何使用我的 javascript 代码创建狗的年龄计算器 HTML 表单?
- mongodb - 将 BsonDocument 写入 MongoDB Spark Scala
- python - 使用sklearn python通过决策树提取数据点的规则路径
- javascript - 如何更新处于组件状态的对象数组?
- c - 在便携式 ZIPPED 文件夹中包含一个 .h 文件
- mysql - 检查记录是否已经存在
- android-studio - 将 OCR 包含到 Android Studio C++ 项目中
- c++ - Boost 文件在 /usr/local/include 和 /usr/include 中有所不同
- recursion - 如何优化我使用递归制作的这个谢尔宾斯基地毯?
- python - 解析协议缓冲区时,字符串字段“google.cloud.language.v1beta2.TextSpan.content”包含无效的 UTF-8 数据