gpt4 book ai didi

python - 带日期限制的总信息

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:55 25 4
gpt4 key购买 nike

我只想根据日期范围按 ID 和给定值求和总计

我尝试过这个:

days=(360)
import datetime
import pandas as pd
group = None
df=pd.read_excel(r'C:\Users\xxxx\Desktop\xxxxx.xlsx')
for i in days:
D = ((datetime.datetime.now()-datetime.timedelta(days=i)))
B = D <= df['DATE']
group = df.groupby('ID')['VALUE'].filter(lambda x: B ).sum()

df:

DATE       ID  VALUE
2019-01-01 1 10
2019-02-01 2 15
2019-03-01 1 12

但是有一个错误

TypeError: the filter must return a boolean result

即使B的类型是bool

我需要的结果是:

    ID Value
1 22
2 15

最佳答案

我相信您需要按 boolean indexing 进行过滤在groupby之前:

 group = df[B].groupby('ID')['VALUE'].sum()

或者:

 D = ((datetime.datetime.now()-datetime.timedelta(days=i)))
B = df.loc[D <= df['DATE'], 'VALUE']
group = B.groupby(df['ID']).sum()

关于python - 带日期限制的总信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55774321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com