gpt4 book ai didi

python - 如何获取自定义间隔中的最后一个日期? - Pandas

转载 作者:行者123 更新时间:2023-11-28 19:35:01 24 4
gpt4 key购买 nike

可能我的例子很大,我的代码在这里:

import pandas as pd
import numpy as np
import io
t = """
name date
a 2005-08-31
a 2005-09-20
a 2005-11-12
a 2005-12-31
a 2006-03-31
a 2006-06-25
a 2006-07-23
a 2006-09-28
a 2006-12-21
a 2006-12-27
a 2007-07-23
a 2007-09-21
a 2007-03-15
a 2008-04-12
a 2008-06-21
a 2008-06-11
b 2005-08-31
b 2005-09-23
b 2005-11-12
b 2005-12-31
b 2006-03-31
b 2006-06-25
b 2006-07-23
b 2006-09-28
b 2006-12-21
b 2006-12-27
b 2007-07-23
b 2007-09-21
b 2007-03-15
b 2008-04-12
b 2008-06-21
b 2008-06-11
"""
data=pd.read_csv(io.StringIO(t),delimiter=' ')#5 space here
data

我想做的是找到每一年开始2005-7-1)和结束2006-06-30的每一年的最后一天,开始2006-7-1 结束 2007-6-30...等等。我的预期输出在这里:

name     date
a 2006-06-25 #the last day of the 2005/7/01 -2006/06/31
a 2007-03-15 #the last day of the 2006/7/01 -2007/06/31
a 2008-06-21 #the last day of the 2007/7/01 -2008/06/31
b 2006-06-25 #the last day of the 2005/7/01 -2006/06/31
b 2007-03-15 #the last day of the 2006/7/01 -2007/06/31
b 2008-06-21 #the last day of the 2007/7/01 -2008/06/31

如何解决这个问题?我想我应该使用 custom

最佳答案

您可以使用单个 groupby 在不回滚的情况下执行此操作:

In [11]: data.date = pd.to_datetime(data.date, format="%Y-%m-%d")

In [12]: df.groupby(["name", pd.Grouper(key="date", freq="AS-JUL")])["date"].max()
Out[12]:
name date
a 2005-07-01 2006-06-25
2006-07-01 2007-03-15
2007-07-01 2008-06-21
b 2005-07-01 2006-06-25
2006-07-01 2007-03-15
2007-07-01 2008-06-21
Name: date, dtype: datetime64[ns]

关于python - 如何获取自定义间隔中的最后一个日期? - Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859942/

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