gpt4 book ai didi

python - Pandas 中提到的按时间帧对数据帧进行分组

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

我有一个类似于下面的数据框:

   detaildate   detailquantity
0 5/6/2014 8550
1 5/8/2014 0
2 3/3/2015 -3250
3 4/14/2015 -3250
4 5/19/2015 3250
5 5/20/2015 -1200
6 2/22/2016 40000
7 4/23/2016 -4500
8 5/23/2016 -2500
9 5/30/2016 -5000
10 4/3/2017 -4750
11 6/5/2017 -2000

现在我想按某个时间范围对这些数据进行分组。例如,如果我每年对其进行分组,我想要以下结果:

   detaildate   detailquantity
0 5/6/2014 8550
1 5/8/2014 0
detaildate detailquantity
0 3/3/2015 -3250
1 4/14/2015 -3250
2 5/19/2015 3250
3 5/20/2015 -1200
detaildate detailquantity
0 2/22/2016 40000
1 4/23/2016 -4500
2 5/23/2016 -2500
3 5/30/2016 -5000
detaildate detailquantity
0 4/3/2017 -4750
1 6/5/2017 -2000

我为其编写了以下代码:

S = pd.to_datetime(df.detaildate)
for i, g in df.groupby([(S - S[0]).astype('timedelta64[Y]')]):
print (g.reset_index(drop=True))

但是,它不是按日历年分组,而是按从开始日期起的 1 年分组。我得到的结果是:

   detaildate   detailquantity
0 5/6/2014 8550
1 5/8/2014 0
2 3/3/2015 -3250
3 4/14/2015 -3250
detaildate detailquantity
0 5/19/2015 3250
1 5/20/2015 -1200
2 2/22/2016 40000
3 4/23/2016 -4500
detaildate detailquantity
0 5/23/2016 -2500
1 5/30/2016 -5000
2 4/3/2017 -4750
detaildate detailquantity
0 6/5/2017 -2000

如何解决这个问题?

另外,我想在方法中编写上述代码并保留时间范围(M,Y,W,D)作为参数。如下所示:

def groupData(df,timeFrame):
S = pd.to_datetime(df.detaildate)
#pass timeFrame as parameter below instead of hardcoded Y
for i, g in df.groupby([(S - S[0]).astype('timedelta64[Y]')]):
print (g.reset_index(drop=True))

如何用我的方法的参数 timeFrame 替换上面的硬编码 Y?

最佳答案

使用series.dt.year()groupby下:

#df.detaildate=pd.to_datetime(df.detaildate)
for i,g in df.groupby(df.detaildate.dt.year):
print(g.reset_index(drop=True))
<小时/>
   detaildate  detailquantity
0 2014-05-06 8550
1 2014-05-08 0
detaildate detailquantity
0 2015-03-03 -3250
1 2015-04-14 -3250
2 2015-05-19 3250
3 2015-05-20 -1200
detaildate detailquantity
0 2016-02-22 40000
1 2016-04-23 -4500
2 2016-05-23 -2500
3 2016-05-30 -5000
detaildate detailquantity
0 2017-04-03 -4750
1 2017-06-05 -2000

关于python - Pandas 中提到的按时间帧对数据帧进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666850/

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