我正在尝试为时间序列创建一组星期几的箱形图(例如,5分钟的温度观测值)。
我的代码:
# 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()
结果:
---------------------------------------------------------------------------
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
我确实通过为每个星期创建DataFrames然后将它们连接到最终的DataFrame来获得成功,但这似乎效率低下......
答案 0 :(得分:9)
首先创建数据框并使用工作日方法来获取星期几:
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
现在转动该表,以便将week_days作为列(也可以将needdays更改为字符串格式的天数,但将其留给您。
x =df.pivot(index='Dates', columns='week_days', values='data')
x.boxplot()
答案 1 :(得分:1)
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())