平均每月从每月的第15天到第15天,或者从第n天到第n天。

huangapple go评论57阅读模式
英文:

Python, how to average month from 15th to 15th of each month, or nth to nth

问题

Sure, here's the translated content without the code part:

我有一个pandas数据框,看起来像下面这样,有一个日期时间列和一个值列。

时间戳
2023年1月1日 100
2023年1月2日 90
....
2023年12月12日 85

我知道如何按月份分组,但我正在寻找一种更精细的方法来计算每月平均值,从一个月的15日到下一个月的15日,看起来像下面这样。

时间戳 平均值
2023年1月15日 - 2023年2月15日 95
2023年2月15日 - 2023年3月15日 93
....
2023年11月15日 - 2023年12月15日 84

我尝试按月分组并将时间列向前推移15天,但这不是精确的,因为每个月的天数不同。

英文:

I have a pandas dataframe that looks like below with a datetime column and a value column

timestamp value
1/1/2023 100
1/2/2023 90
....
12/12/2023 85

i know how to group from month to month, but looking for something a bit more nuanced to calculate the average monthly value but from the 15th of one month to the 15th of the next month, looking something like below

timestamp mean_value
1/15/2023 - 2/15/2023 95
2/15/2023 - 3/15/2023 93
....
11/15/2023 - 12/15/2023 84

I tried grouping from month to month and shifting a time column by 15, but this isnt exact since every month has a different amount of days..

答案1

得分: 1

我相信以下任何一种方法都应该有效:

(df.groupby(df['date'].dt.day.eq(15).cumsum(), as_index=False)
 .agg({'date': lambda x: '{} - {}'.format(*x.dt.strftime('%m/%d/%Y').iloc[[0, -1]].tolist()),
       'value': 'mean'}))

或者

(df.groupby((df['date'] - pd.to_timedelta('14D')).dt.to_period('M'), as_index=False)
 .agg({'date': lambda x: '{} - {}'.format(*x.dt.strftime('%m/%d/%Y').iloc[[0, -1]].tolist()),
       'value': 'mean'}))
英文:

I believe either of these should work:

(df.groupby(df['date'].dt.day.eq(15).cumsum(),as_index=False)
 .agg({'date':lambda x: '{} - {}'.format(*x.dt.strftime('%m/%d/%Y').iloc[[0,-1]].tolist()),
       'value':'mean'}))

or

(df.groupby((df['date'] - pd.to_timedelta('14D')).dt.to_period('M'),as_index=False)
 .agg({'date':lambda x: '{} - {}'.format(*x.dt.strftime('%m/%d/%Y').iloc[[0,-1]].tolist()),
       'value':'mean'}))

huangapple
  • 本文由 发表于 2023年4月20日 00:27:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定