【问题标题】:Matplotlib: plot number of observations per minute across all Mondays in a yearMatplotlib:一年中所有星期一每分钟的观察次数
【发布时间】:2015-11-27 11:10:18
【问题描述】:

我有一个 pandas DataFrame,其中一列是一堆日期(日期时间类型)。我正在尝试将一年中所有星期一的每分钟观察次数与当天的分钟数进行对比。

例如,假设我的数据中有两个星期一,在第一个星期一的 09:01 有 3 个观测值,在第二个星期一的 09:01 有 4 个观测值。我想针对 9*60+1=541 绘制 7 (3+4) (也就是说,09:01 是一天开始以来的第 541 分钟)。我是这样开始的:

def minutes_in_day(arg):
    #returns minute number in day  
    return arg.hour*60+arg.minute

def get_day(arg):
    return arg.isocalendar()[2]

# df is my pandas dataframe
df['day']=df['my_datetime_variable'].apply(get_day)
df['minute']=df['my_datetime_variable'].apply(minutes_in_day)
group=df.groupby(['day','minute'])
my_data=group['whatever_variable'].count()

my_data 有两个索引:一个从 1(星期一)到 7(星期日)的日索引和一个从可能 0 到可能 24*60-1=1439 的分钟索引。仅当日索引为 1 时,如何使用 matplotlib(pyplot) 绘制观察计数与分钟索引?

【问题讨论】:

    标签: python datetime matplotlib


    【解决方案1】:

    我认为这或多或少是你想要的:

    #import modules
    import random as randy 
    import numpy as np
    import pandas as pd
    
    #create sample dataset
    idx=randy.sample(pd.date_range(start='1/1/2015',end='5/5/2015',freq='T'),2000)
    idx.sort()
    dfm=pd.DataFrame({'data':np.random.randint(0,2,len(idx))},index=idx)
    
    #resample to fill in the gaps and groupby day of the week (0-6) and time
    dfm=dfm.resample('T')
    dfm=dfm.groupby([dfm.index.dayofweek,dfm.index.time]).count()
    
    #Select monday (the '0th' day of the week) 
    dfm=dfm.loc[0]
    
    #plot
    dfm.plot(title="Number of observations on Mondays",figsize=[12,5])
    

    给予

    正如您在pandas.DatetimeIndex docs 中看到的,dayofweek 属性返回星期一=0 - 星期日=6 的星期几,time 属性返回numpy 数组datetime.time

    【讨论】:

    • 谢谢,您的回答很有帮助。我的问题是我的日期时间变量中也有秒数——这就是我最初使用minutes_in_day 函数的原因。您知道如何使用index.time 按分钟分组吗?谢谢
    • 为了避免这样的事情,最好给出一个可重复的例子,例如像我一样编造一些数据。要获得您想要的,您可以将groupby 更改为dfm.groupby([dfm.index.dayofweek,dfm.index.hour,dfm.index.minute]).count()。 (或者,如果您想将 DatetimeIndex 从秒舍入到分钟,您可以使用 pd.DatetimeIndex(((dfm.index.asi8/(1e9*60)).round()*1e9*60).astype(np.int64)).v‌​alues,如 here 所述。)
    猜你喜欢
    • 2023-03-13
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2021-05-03
    • 1970-01-01
    相关资源
    最近更新 更多