【问题标题】:Set values of groups in pandas conditionally python有条件地在熊猫中设置组的值python
【发布时间】:2013-06-14 06:48:21
【问题描述】:

我有一个包含以下列的数据框:

duration, cost, channel 
  2       180      TV1
  1       200      TV2
  2       300      TV3
  1       nan      TV1
  2       nan      TV2
  2       nan      TV3
  2       nan      TV1
  1       40       TV2
  1       nan      TV3

一些成本值是 nans,要填充它们,我需要执行以下操作:

  • 按频道分组
  • 在一个频道内,将可用成本相加并除以 * 出现次数(平均)
  • 为该通道内的所有行重新分配值:
    • 如果持续时间 = 1,则成本 = 平均 * 1.5
    • 如果持续时间 = 2,则成本 = 平均

示例: TV2 频道,我们有 3 个条目,其中一个条目的成本为零。所以我需要做以下事情:

average = 200+40/3 = 80
if duration = 1, cost = 80 * 1.5 = 120

duration, cost, channel 
  2       180      TV1
  1       120      TV2
  2       300      TV3
  1       nan      TV1
  2       80       TV2
  2       nan      TV3
  2       nan      TV1
  1       120      TV2
  1       nan      TV3

我知道我应该执行 df.groupby('channel') 然后将函数应用于每个组。 问题是我不仅需要修改空值,如果 1 个成本为空,我还需要修改组内的所有成本值。

任何提示帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: python group-by pandas missing-data


    【解决方案1】:

    如果我正确理解你的问题,你想要这样的东西:

    def myfunc(group):
    
        # only modify cost if there are nan's
        if len(group) != group.cost.count():
    
            # set all cost values to the mean
            group['cost'] = group.cost.sum() / len(group)
    
            # multiply by 1.5 if the duration equals 1
            group['cost'][group.duration == 1] = group['cost'] * 1.5
    
        return group
    
    
    df.groupby('channel').apply(myfunc)
    
       duration  cost channel
    0         2    60     TV1
    1         1   120     TV2
    2         2   100     TV3
    3         1    90     TV1
    4         2    80     TV2
    5         2   100     TV3
    6         2    60     TV1
    7         1   120     TV2
    8         1   150     TV3
    

    【讨论】:

    • 谢谢!但是 df 中的成本列未分配新值。当我分配 df.cost = df.groupby('channel').apply(myfunc) 时,我得到了一个错误。
    • 在这种情况下,应用值已经返回完全相同的 df,只是成本值不同。所以你可以这样做:df = df.groupby('channel').apply(myfunc)。但是,如果您坚持只修改成本列,这也可以:df['cost'] = df.groupby('channel').apply(myfunc)['cost']。但我不会使用后者,因为索引的更改可能会导致错位,即使在这种情况下它也可以。
    【解决方案2】:

    在新版本的 Pandas 中,代码应该改为

    def myfunc(group):
        # only modify cost if there are nan's
        if len(group) != group.cost.count():
    
            # set all cost values to the mean
            group['cost'] = group.cost.sum() / len(group)
    
            # multiply by 1.5 if the duration equals 1
            _ = group.set_value(group[group.duration == 1].index, 'cost', group['cost'] * 1.5)
    
        return group
    

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 2020-01-12
      • 2020-09-11
      相关资源
      最近更新 更多