python - 使用 panda 的分配功能时出现 KeyError
问题描述
我在下面有数据框,我希望根据收入和预算创建新变量“profit_loss”和“profit_margin”。
revenue budget
0 1513528810 150000000
1 378436354 150000000
2 295238201 110000000
3 2068178225 200000000
4 1506249360 190000000
我尝试使用 pandas assign()方法创建新变量,但出现以下错误。
d.assign(profit_loss = (d['revenue'] - d['budget']),
profit_loss_margin = (d['profit_loss'] * 100 / d['revenue']),
financial_status = d['profit_loss'].apply(lambda num: 'Profit-Making' if num > 0 else 'Loss-
Making'))
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2895 return self._engine.get_loc(casted_key) 2896 except KeyError as err:
-> 2897 raise KeyError(key) from err 2898 2899 if tolerance is not None:
KeyError: 'profit_loss'
但是,下面的代码工作得很好。
d.assign(profit_loss = (d['revenue'] - d['budget']))
请告知我在以前的代码中是否犯了任何错误?
解决方案
您需要lambda
像这里一样使用新创建的列profit_loss
:
df = d.assign(profit_loss = (d['revenue'] - d['budget']),
profit_loss_margin = lambda x: (x['profit_loss'] * 100 / x['revenue']),
financial_status = lambda x: x['profit_loss'].apply(lambda num: 'Profit-Making' if num > 0 else 'Loss- Making'))
print (df)
revenue budget profit_loss profit_loss_margin financial_status
0 1513528810 150000000 1363528810 90.089386 Profit-Making
1 378436354 150000000 228436354 60.363216 Profit-Making
2 295238201 110000000 185238201 62.741949 Profit-Making
3 2068178225 200000000 1868178225 90.329654 Profit-Making
4 1506249360 190000000 1316249360 87.385887 Profit-Making
推荐阅读
- javascript - 我想将对象的值发送到服务器
- java - 在 Go 中使用 DSA 签署 SHA-256 哈希
- http - Golang:将字节切片数组转换为整数数组
- javascript - 使用 Javascript 函数将文本添加到 html 元素
- python-3.x - 尝试在 Mac 上的 python 3.9.6 上使用 PyAudio
- javascript - 如何在日期选择器中禁用自定义日期以及以前的日期?
- python - Python - 从互联网获取 .arff 文件作为字典类型
- odoo - 如何从 odoo URL 中找出 odoo db 链接。“thiscotime-thisco-erp-testing-3132300.dev”不存在
- html - 如何将伪元素(之前)与所选元素水平对齐
- r - 如何识别两个数据矩阵之间的哪些列和行匹配?