python - 更改 pandas groupby 使用的函数中的值

标签 python pandas pandas-groupby

我正在执行以下操作:

def percentage(x):
    return x[(x<=5)].count() / x.count() * 100

full_data = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage})

但我想这样做groupby连续具有多个值,例如 x<=7 , x<=9 , x<=11percentage功能。

除了编写多个函数并调用它们之外,最简单的方法是什么?

所以基本上我想避免做这样的事情:

def percentage_1(x):
    return x[(x<=5)].count() / x.count() * 100

full_data_1 = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage_1})

def percentage_2(x):
    return x[(x<=7)].count() / x.count() * 100

full_data_2 = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage_2})

# etc.

最佳答案

您可以重写您的函数 - 创建由 bool 掩码填充的新列,然后使用 Series.mul 聚合 mean 和最后一个倍数 100 :

n = 3

full_data['new'] = full_data['Volume'] <= n
full_data = full_data.groupby(['Id', 'Week_id'])['new'].mean().mul(100).reset_index()

具有功能的解决方案:

def per(df, n):
    df['new'] = df['Volume'] <= n
    return df.groupby(['Id', 'Week_id'])['new'].mean().mul(100).reset_index()

编辑:来自github的解决方案:

full_data = pd.DataFrame({
        'Id':list('XXYYZZXYZX'),
         'Volume':[2,4,8,1,2,5,8,2,6,4],
         'Week_id':list('aaabbbabac')
})

print (full_data)

val = 5
def per(c):
    def f1(x):
        return x[(x<=c)].count() / x.count() * 100
    return f1

full_data2 = full_data.groupby(['Id', 'Week_id']).agg({'Volume': per(val)}).reset_index()
print (full_data2)
  Id Week_id      Volume
0  X       a   66.666667
1  X       c  100.000000
2  Y       a    0.000000
3  Y       b  100.000000
4  Z       a    0.000000
5  Z       b  100.000000

def percentage(x):
    return x[(x<=val)].count() / x.count() * 100

full_data1 = full_data.groupby(['Id', 'Week_id'], as_index=False).agg({'Volume': percentage})

print (full_data1)
  Id Week_id      Volume
0  X       a   66.666667
1  X       c  100.000000
2  Y       a    0.000000
3  Y       b  100.000000
4  Z       a    0.000000
5  Z       b  100.000000

关于python - 更改 pandas groupby 使用的函数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54648867/

相关文章:

python - 包含初始化集的数据类?

python - 计算 DataFrame 中运行的总天数并将值插入新列

python - 在python中将json转换为dataframe

python - 查找 pandas Dataframe 列的唯一行,其中第二列的所有值都是 NaN

python - GAE 中的 fetch() 获取什么?

python - HTML 结构转化为网络图

python - 制作条形图来表示 Pandas Series 中出现的次数

python - pandas read_csv 将所有值放在一列和一行中

python - 使用日期时间之前和之后的位置从 DataFrame 中插入位置

Pandas - 查找两个或多个满足条件的行