【问题标题】:How to calculate monthly and weekly averages from a dataframe using python?如何使用 python 从数据框中计算月平均值和周平均值?
【发布时间】:2022-01-07 22:21:52
【问题描述】:

以下是我的数据框。如何在 python 中从这个数据框中计算月平均值和周平均值?我需要打印月份开始&结束和周开始&结束然后是月和周的平均值

**Input
SAMPLE DATASET**            
kpi_id  kpi_name    run_date    value
1       MTTR       5/17/2021    15
2       MTTR       5/18/2021    16
3       MTTR       5/19/2021    17
4       MTTR       5/20/2021    18
5       MTTR       5/21/2021    19
6       MTTR       5/22/2021    20
7       MTTR       5/23/2021    21
8       MTTR       5/24/2021    22
9       MTTR       5/25/2021    23
10      MTTR       5/26/2021    24
11      MTTR       5/27/2021    25


**expected output**
**monthly_mean**            
kpi_name    month_start month_end   value(mean)
    MTTR    5/1/2021    5/31/2021   20
**weekly_mean**         
kpi_name    week_start  week_end    value(mean)
    MTTR    5/17/2021   5/23/2021   18
    MTTR    5/24/2021   5/30/2021   23.5

【问题讨论】:

  • 可以看看下面的帖子:Rolling Window
  • 在我的情况下它不起作用...请帮助如何做到这一点?

标签: python pandas dataframe


【解决方案1】:

igrolvr 扩展answer 以匹配您的预期输出:

# transformation from string to datetime for groupby
df['run_date'] = pd.to_datetime(df['run_date'], format='%m/%d/%Y')

# monthly
# The groupby() will extract the last date in period, 
# reset_index() will make the group by keys to columns
monthly = df.groupby(by=['kpi_name', pd.Grouper(key='run_date', freq='M')])['value'].mean().reset_index()

# Getting the start of month 
monthly['month_start'] = monthly['run_date'] - pd.offsets.MonthBegin(1)

# Renaming the run_date column to month_end
monthly = monthly.rename({'run_date': 'month_end'}, axis=1)
print(monthly)

# weekly
# The groupby() will extract the last date in period, 
# reset_index() will make the group by keys to columns
weekly = df.groupby(by=['kpi_name', pd.Grouper(key='run_date', freq='W')])['value'].mean().reset_index()

# Getting the start of week and adding one day, 
# because start of week is sunday
weekly['week_start'] = weekly['run_date'] - pd.offsets.Week(1) + pd.offsets.Day(1)

# Renaming the run_date column to week_end
weekly = weekly.rename({'run_date': 'week_end'}, axis=1)
print(weekly)

【讨论】:

  • 非常感谢!一整天,我都被这个困住了。尝试不同的事情。感谢您为此付出的时间和精力。
  • 答案的优秀扩展,谢谢
【解决方案2】:

groupby是你的朋友

monthly = df.groupby(pd.Grouper(key='run_date', freq='M')).mean() 
weekly = df.groupby(pd.Grouper(key='run_date', freq='W')).mean() 

【讨论】:

  • 我收到此错误:TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但有一个“索引”实例
  • 像这样转换你的 run_date 列:df['run_date'] = pd.to_datetime(df['run_date'],format='%d/%m/%Y') 其中df 是你的数据框
  • @PhilLeh 的好点子,您应该将 run_date 列作为类似日期时间的对象,以便可以应用 groupby 方法
  • 你能帮忙解决上述情况吗...我应该从数据集中获取开始和结束日期,然后它应该得到特定时期的平均值
  • @PhilLeh 你能帮我解决这个问题吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 2021-08-18
  • 2018-06-22
  • 1970-01-01
相关资源
最近更新 更多