【发布时间】:2020-12-08 08:32:11
【问题描述】:
我在下面有数据框,我希望根据收入和预算创建新变量“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']))
请告知我之前的代码是否有任何错误?
【问题讨论】:
标签: python python-3.x pandas dataframe