You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas使用groupby+Lambda多条件分组失效问题咨询

问题原因与修正方案
  • 错误原因:s3的多条件筛选语法逻辑错误
    你把两个独立的筛选结果(x[x['status'] =='OPEN']和x[x['status2'] =='NEW'])直接用&拼接,这会尝试对两个DataFrame做按位与运算,而非合并筛选条件。同时count()的调用位置也不对,应该先合并条件筛选出目标行,再对account_number计数。

  • 修正后的s3代码:

s3 = g.apply(lambda x: x[(x['status'] == 'OPEN') & (x['status2'] == 'NEW')]['account_number'].count())
  • 更高效的替代写法:
    如果仅需统计分组内符合条件的数量,用groupby结合sum比apply性能更优,示例如下:
# 先给符合双条件的行标记为1,其余为0,再分组求和
dfopenclosed['flag'] = ((dfopenclosed['status'] == 'OPEN') & (dfopenclosed['status2'] == 'NEW')).astype(int)
s3 = dfopenclosed.groupby('week')['flag'].sum()

内容的提问来源于stack exchange,提问作者Michael K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:34:56