散景选择小部件日期时间不一致(熊猫)

时间:2018-02-14 21:53:06

标签: pandas datetime bokeh

我有一个充满日期和交易的数据框:

ENTRYDATE | TRANSACTIONS
2017-01-02   20
2017-01-16   51
..
2018-02-01   12

我有一个选择小部件,用户可以通过['day,'weekly','monthly',annually]

查看数据

选择dailyannually后,图表会准确更新并将数据汇总为每日或每年的交易。但是,当选择weeklymonthly时,似乎情节将{201}从2018年1月和2018年2月的transactions捆绑到2017年1月和2月的数据中,超过了2017年的数量。为什么会这样?我该如何修理?

以下是我的相关代码:

import pandas as pd
from bokeh.models import ColumnDataSource,DatetimeTickFormatter, NumeralTickFormatter, HoverTool, Select
from bokeh.plotting import figure
from bokeh.io import curdoc

df2=df[['ENTRYDATE']] 
df2['ENTRYDATE']=pd.to_datetime(df2['ENTRYDATE'],infer_datetime_format=True)

#set data sources
dfdate=(df2.groupby([df2['ENTRYDATE'].dt.date]).size().reset_index(name='Transactions'))
dfweek=(df2.groupby([df2['ENTRYDATE'].dt.week]).size().reset_index(name='Transactions'))
dfmonth=(df2.groupby([df2['ENTRYDATE'].dt.month]).size().reset_index(name='Transactions'))
dfyear=(df2.groupby([df2['ENTRYDATE'].dt.year]).size().reset_index(name='Transactions'))

source1=ColumnDataSource(data=dfdate)
source2=ColumnDataSource(data=dfweek)

p=figure(plot_width=800,plot_height=500, y_axis_label="Count")

p.line(x="ENTRYDATE",y="Transactions",color='blue', source=source1)
p.xaxis.formatter=DatetimeTickFormatter()

#update function
def update_plot(attr, old, new):
    if new=='Daily':
        source1.data={"ENTRYDATE":dfdate["ENTRYDATE"],"Transactions":dfdate["Transactions"]}
    elif new=='Weekly':
        source1.data=source2.data
    elif new=='Monthly':
        source1.data={"ENTRYDATE":dfmonth["ENTRYDATE"],"Transactions":dfmonth["Transactions"]}
    elif new=='Annually':
        source1.data={"ENTRYDATE":dfyear["ENTRYDATE"],"Transactions":dfyear["Transactions"]}
#selecttool
select=Select(title='Choose Your Time Interval:', options=['Daily','Weekly','Monthly','Annually'], value='daily')
select.on_change('value',update_plot)
layout=row(select, p)
curdoc().add_root(layout)

1 个答案:

答案 0 :(得分:0)

一个想法是将年份添加到周数或月数,然后按升序排序。 df['YearWk']=df['ENTRYDATE'].dt.strftime('%Y.%W')

相关问题