Pandas Dataframe,获取每个星期一凌晨 1 点的平均值 [英] Pandas Dataframe, getting average value for each monday 1 Am

查看:55
本文介绍了Pandas Dataframe,获取每个星期一凌晨 1 点的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 DataFrame 如下所示:

my DataFrame looks like this:

index                   value
2016-03-21 00:00:00     0.613014
2016-03-21 01:00:00     0.596383
2016-03-21 02:00:00     0.623570
2016-03-21 03:00:00     0.663350
2016-03-21 04:00:00     0.677817
2016-03-21 05:00:00     0.727116
2016-03-21 06:00:00     0.920279
2016-03-21 07:00:00     1.205863
2016-03-21 08:00:00     0.880946
2016-03-21 09:00:00     0.186947
2016-03-21 10:00:00     -0.563276
2016-03-21 11:00:00     -1.249595
2016-03-21 12:00:00     -1.596035
2016-03-21 13:00:00     -1.886954
2016-03-21 14:00:00     -1.912325
2016-03-21 15:00:00     -1.750623
...     
2016-06-20 23:00:00     2.125791

我试图在数据框中获得每个星期一凌晨 1 点的平均值.最后,我想要一个代表数据帧平均周"的输出,以便我可以可视化一周的进程.

I am trying to get the average for each monday at 1 am in the dataframe. In the end I want to have an output that represents the 'average week' of the dataframe, so I can visualize the course of the week.

我希望我能清楚地表达自己.

I hope I could express myself clearly.

感谢您的帮助!

推荐答案

我不知道如何解释你的问题,所以这里有两个答案(针对不同的问题)

I'm not sure how to interpret your question, so here are two answers (to different questions)

获取星期一凌晨 1:00 发生的所有值的平均值(输出将是单个标量):

# Make sure the index is a pd.datetime object
df.index = pd.to_datetime(df.index)

# find all rows which occur on a monday and at 01:00:00, and take the mean
monday_means = (df.loc[(df.index.weekday_name == 'Monday') &
                       (df.index.time == pd.to_datetime('01:00:00').time())]
                .mean()
                .to_frame('Monday 1 Am'))

获取前一周的平均值,一周从周一凌晨 1:00 开始(输出将是一个系列):

# Make sure the index is a pd.datetime object
df.index = pd.to_datetime(df.index)

# Create a column for week number, which counts consecutively every monday at 1:00:00
df['week_number'] = ((df.index.weekday_name == 'Monday') &
                     (df.index.time == pd.to_datetime('01:00:00').time())
                     .cumsum())


# Groupby week number and get the mean
df.groupby('week_number').mean()

或者,更简单(但不太灵活,它会在星期一午夜而不是凌晨 1 点开始这一周):

Or, more simply (but less flexible, it will start the week on monday at midnight, rather than 1 am):

df.groupby(pd.Grouper(freq='W')).mean()

这篇关于Pandas Dataframe,获取每个星期一凌晨 1 点的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆