python - group-by + case when 等价

标签 python pandas group-by dataframe

要选择:

select
    user_id,
    max(case when value > 0 then timestamp else 0 end) as max_timestamp_when_value_is_positive
from df
group by user_id

什么是正确的聚合方式?

groupped = raw_data.groupby('user_id')
res = groupped.agg({<how-to-do-described-aggregation?>})

更新 解释和示例。

In [2]: df = pd.DataFrame({'user_id': [1, 1, 1, 2, 2, 3, 3, 3, 3],
                           'timestamp': [100, 200, 300, 10, 110, 10, 110, 210, 250],
                           'value': [0, 1, 0, 0, 0, 0, 10, 0, 1]})

In [3]: groupped = df.groupby('user_id')

In [4]: res = groupped.agg({'timestamp': [min, max],
                            'value': lambda x: sum(x > 0),
                            <described-magic>})

In [5]: res
Out[5]: 
        timestamp         value   <...magic...>
              min  max <lambda>
user_id                        
1             100  300        1    200
2              10  110        0    0
3              10  250        2    210

魔法是我想要的。

最佳答案

创建一个新列 positive_value_timestamp 作为

df['positive_value_timestamp'] = df.timestamp * df.value.apply(lambda x: 1 if x > 0 else 0)

分组时,取该列的max

res = df.groupby('user_id').agg(
    {
        'timestamp': [min, max],
        'value': sum,
        'positive_value_timestamp': max
    })

关于python - group-by + case when 等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30167822/

相关文章:

python - 如何在 Pandas DataFrame where 子句中使用特定列的值?

python - Pandas 访问最后一个非空值

SQL - 按 ID 分组和从变量起点开始的时间间隔

MySQL Group By 并水平显示

python - 无法上传 > ~2GB 到 Google Cloud Storage

python - 机器人框架访问测试套件元数据中的关键字

python - 如何获取所有子目录和文件的列表及其按大小排序的大小?

python - 整个数据帧中 FOR 循环中的 IF 语句 : performance improvement

Python - Matplotlib 使用 pandas 数据框时绘制不正确的图形

mysql - 我如何从表中的两个查询中获取公共(public)值并将其与 MySql 中的另一个表连接?