Python Matplotlib:绘制一年中所有周一每分钟的观测数
我有一个pandas数据框,其中一列是一组日期(datetime类型)。我试图用一年中所有周一的每分钟观察次数与一天的分钟数进行对比 例如,假设我的数据中有两个星期一,第一个星期一09:01有3个观测值,第二个星期一09:01有4个观测值。我想绘制7(3+4)与9*60+1=541的对比图(也就是说,09:01是一天开始后的541分钟)。我是这样开始的:Python Matplotlib:绘制一年中所有周一每分钟的观测数,python,datetime,matplotlib,Python,Datetime,Matplotlib,我有一个pandas数据框,其中一列是一组日期(datetime类型)。我试图用一年中所有周一的每分钟观察次数与一天的分钟数进行对比 例如,假设我的数据中有两个星期一,第一个星期一09:01有3个观测值,第二个星期一09:01有4个观测值。我想绘制7(3+4)与9*60+1=541的对比图(也就是说,09:01是一天开始后的541分钟)。我是这样开始的: def minutes_in_day(arg): #returns minute number in day return
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_数据有两个指数:从1(周一)到7(周日)的日指数和从0到24*60-1=1439的分钟指数。当日指数为1时,如何使用matplotlib(pyplot)根据分钟指数绘制观测计数 我想这或多或少是你想要的:
#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])
给予
如中所述,
dayofweek
属性返回星期一=0-星期日=6的一周中的某一天,time
属性返回numpy
数组datetime.time
谢谢,你的回答很有帮助。我的问题是datetime变量中还有秒,这就是我最初使用minutes\u in_day
函数的原因。你知道如何使用索引.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值
,如上所述。)