python - 有条件地设置 Pandas 中组的值python

标签 python group-by pandas missing-data

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

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,要填充它们,我需要执行以下操作:

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

例子: TV2 channel ,我们有 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 个成本为空,我还需要修改组内的所有成本值。

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

谢谢!

最佳答案

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

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

关于python - 有条件地设置 Pandas 中组的值python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17102647/

相关文章:

python - 尝试通过标题获取数据框列时出现类型错误

mysql - 左连接和计数在 MYSQL 中不能正常工作

mysql where + group by 很慢

python - 仅当有一个行具有空值时,才向前填充数据框中的一列

python - 拟合曲线: which model to describe distribution in weighted knowledge graphs

python - 在 Cython 中获取 numpy 数组子集的最快方法

python - 如何使用python计算文本文件中的总行数

python - 蝗虫,上传测试

python - 删除重复项,但保留每组给定列中具有最大值的行

python-3.x - 从 Pandas 数据框中的一个或多个字符串值创建一个列表