【问题标题】:KeyError when using panda's assign function使用 panda 的分配功能时出现 KeyError
【发布时间】: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


    【解决方案1】:

    您需要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
    

    【讨论】:

    • 谢谢。有用。我虽然可以跳过“lambda”来简化我的代码。
    【解决方案2】:

    您正在分配 df 变量“profit_loss”并尝试使用它在同一个调用中分配新变量。 Python 将在调用函数之前解析所有参数。因此,当它尝试在您的第二个和第三个参数中解析 d['profit_loss'] 时,它还不存在,因为尚未调用 assign。试试

    d.assign(profit_loss = (d['revenue'] - d['budget']))
    d.assign(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'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2013-05-05
      • 1970-01-01
      • 2017-06-17
      • 2014-09-15
      • 1970-01-01
      相关资源
      最近更新 更多