Best way to generate day-of-week boxplots from a Pandas timeseries

橙三吉。 提交于 2019-12-20 21:00:13

问题


i am trying to create a set of day-of-week boxplots for a timeseries (e.g. 5-minute temperature observations).

My code:

# ts is our timeseries
ts = df.SomeColumn

dow_map = {}
days = ['MON','TUE','WED','THU','FRI','SAT','SUN']
dow_idx = ts.index.dayofweek

i = 0
for d in days:
    dow_map[d] = ts[dow_idx == i]
    i = i + 1

df = pd.DataFrame(dow_map)
df.boxplot()

results in:

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-898-6070c45e4c4b> in <module>()
     41     i = i + 1
     42 
---> 43 df = pd.DataFrame(dow_map)
     44 df.boxplot()
...
Exception: Reindexing only valid with uniquely valued Index objects

I did find succcess by creating DataFrames for each day-of-week and then concat-ing them into a final DataFrame, but this seems inefficient...


回答1:


1st Create data frame and use weekdays method to get days of week:

import pandas as pd
import numpy.random as random
n=1000
df = pd.DataFrame(random.randn(n), pd.date_range('2010-01-01', periods=n), columns=["data"])
df['Dates'] = df.index
df['week_days'] =df.index.weekday
df

now pivot that table so that the week_days are as columns (could also change the needdays to string formats of days but leaving that for you.

x =df.pivot(index='Dates', columns='week_days', values='data')
x.boxplot()




回答2:


import locale, calendar
# for example pl_PL
locale.setlocale(locale.LC_ALL, 'pl_PL.UTF-8')
x = x.rename_axis(lambda x: calendar.day_abbr[x].capitalize())


来源:https://stackoverflow.com/questions/17194581/best-way-to-generate-day-of-week-boxplots-from-a-pandas-timeseries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!