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

如何让Pandas按日累计计算,实现每日统一投资决策标记?

问题:按日累计生成统一投资标记的Pandas代码调整

需求背景

日常记录新的投资机会,但结果列(lay)仅在每日午夜进行登记。核心规则:

  • 每日所有投资机会的invest标记,由前一日的累计值决定:累计值>0则当日所有记录标记为True,否则为False
  • 当日所有lay值汇总后更新累计值,用于次日的投资判断

示例1:累计值计算错误

原始CSV数据

clock_now,competition,market_name,lay
2022/12/30,A,B,-1
2022/12/31,A,B,1.28
2023/01/01,A,B,-1
2023/01/02,A,B,1
2023/01/03,A,B,1
2023/01/04,A,B,
2023/01/04,A,B,
2023/01/04,A,B,

当前代码

import pandas as pd

df = pd.read_csv('example.csv')
combinations = [['market_name', 'competition']]
for cbnt in combinations:
    df['invest'] = (df.groupby(cbnt)['lay']
                      .apply(lambda s: s.cumsum().shift())
                      .gt(df['lay'])
                   )

    df['cumulative'] = (df.groupby(cbnt)['lay']
                      .apply(lambda s: s.cumsum().shift())
                   )

    print(df[['clock_now','invest','cumulative']])

错误输出

clock_now  invest  cumulative
0  2022/12/30   False         NaN
1  2022/12/31   False       -1.00
2  2023/01/01    True        0.28
3  2023/01/02   False       -0.72
4  2023/01/03   False        0.28
5  2023/01/04    True        1.28
6  2023/01/04    True        0.28
7  2023/01/04    True       -0.72

预期输出

clock_now  invest  cumulative
0  2022/12/30   False         NaN
1  2022/12/31   False       -1.00
2  2023/01/01    True        0.28
3  2023/01/02   False       -0.72
4  2023/01/03    True        0.28
5  2023/01/04    True        1.28
6  2023/01/04    True        0.28
7  2023/01/04    True       -1.72

示例2:同一日期标记不一致

原始CSV数据

clock_now,competition,market_name,lay
2022/08/09,A,B,-1.0
2022/08/12,A,B,1.28
2022/09/07,A,B,-1.0
2022/10/15,A,B,1.0
2022/10/15,A,B,-1.0
2022/11/20,A,B,1.0

当前错误输出

clock_now  invest  cumulative
0  2022/08/09   False         NaN
1  2022/08/12   False       -1.00
2  2022/09/07    True        0.28
3  2022/10/15   False       -0.72
4  2022/10/15    True        0.28
5  2022/11/20   False       -0.72

预期输出(当日所有记录标记统一)

clock_now  invest  cumulative
0  2022/08/09   False         NaN
1  2022/08/12   False       -1.00
2  2022/09/07    True        0.28
3  2022/10/15   False       -0.72
4  2022/10/15   False        0.28
5  2022/11/20   False       -0.72

问题

如何调整Pandas代码,实现按日累计规则,基于前一日累计结果生成当日统一的invest标记?


内容的提问来源于Stack Exchange,提问作者Digital Farmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:55:12