Skip to main content
 首页 » 编程设计

python Pandas : case statement in agg function

2025年04月02日16yjmyzz

我有这样的sql语句:

select id 
        , avg(case when rate=1 then rate end) as "P_Rate" 
        , stddev(case when rate=1 then rate end) as "std P_Rate", 
        , avg(case when f_rate = 1 then f_rate else 0 end) as "A_Rate" 
        , stddev(case when f_rate = 1 then f_rate else 0 end) as "std A_Rate" 
from ( 
 select id, connected_date,payment_type,acc_type, 
  max(case when is s_rate > 1 then 1 else 0 end) / count(open) as rate 
  sum(case when is hire_days <= 5 and paid>1000 then 1 else 0 end )/count(open) as f_rate 
from analysis_table where alloc_date <= '2016-01-01' group by 1,2 
) a group by id 

我尝试使用 Pandas 重写: 首先,我将为“内部”表创建数据框:

filtered_data = data.where(data['alloc_date'] <= analysis_date) 

然后我将这些数据分组

grouped = filtered_data.groupby(['id','connected_date']) 

但是我必须使用什么来过滤每一列并在其上使用 max/sum。

我试过这样的:

`def my_agg_function(hire_days,paid,open): 
     r_arr = [] 
     if hire_days <= 5 and paid > 1000: 
        r_arr.append(1) 
     else: 
        r.append(0) 
     return np.max(r_arr)/len(????) 
inner_table['f_rate'] = grouped.agg(lambda row: my_agg_function(row['hire_days'],row['paid'],row['open'])` 

还有类似的速率

请您参考如下方法:

你应该在你的问题中加入一点 DataFrame 以使其更容易回答。

根据您的需要,您可能希望使用 groupby 数据帧的 agg 方法。假设您有以下数据框:

    connected_date  id      number_of_clicks    time_spent 
0   Mon             matt    15                  124 
1   Tue             john    13                  986 
2   Mon             matt    48                  451 
3   Thu             jack    68                  234 
4   Sun             john    52                  976 
5   Sat             sabrina 13                  156 

并且您想获得用户每天花费的时间和单次 session 中的最大点击次数的总和。然后以这种方式使用 groupby:

df.groupby(['id','connected_date'],as_index = False).agg({'number_of_clicks':max,'time_spent':sum}) 

输出:

    id      connected_date  time_spent  number_of_clicks 
0   jack    Thu             234         68 
1   john    Sun             976         52 
2   john    Tue             986         13 
3   matt    Mon             575         48 
4   sabrina Sat             156         13 

请注意,为了输出清晰,我只传递了 as_index=False。