【问题标题】:How to plot mensual boxplots for a specific column in a datetime indexed dataframe?如何绘制日期时间索引数据框中特定列的手动箱线图?
【发布时间】:2021-06-15 04:41:52
【问题描述】:

我真的是 python/pandas 的新手,遇到了一个我无法弄清楚的问题。

我得到了一个数据框,其中包含几列,其中包含一整年每小时的值。我使用日期时间对其进行了索引。类似的东西(但当然更长):

 d={'date':['01/01/2019 00:00','01/01/2019 01:00','01/01/2019 02:00'],'ex_1':[456,421,478],'ex_2':[243,145,2146],'ex_3':[123,1546,5643]}
df=pd.DataFrame(data=d)
df['date']=pd.to_datetime(df['date'])
df=df.set_index(['date'])

我想通过使用 seaborn 或 matplotlib 绘制箱线图来研究此数据框,但我想为一年中的每个月仅针对特定列获取男性箱线图(因此,一个图表上有 12 个框,针对特定列)和不知道怎么弄。。。

我尝试使用 df.loc 之类的

df.loc['2019-01-01':'2019-01-31']['ex_3']

但我无法以某种方式将其处理成箱线图,看起来结果不再是数据框了。

我认为可能是通过选择我要查找的特定列并创建一个新数据框来创建一个新数据框,其中每列将是一个月并且包含该月的特定数据,但我无法弄清楚也没有。

我只是不知道该往哪个方向走。

对不起,如果这是一个愚蠢的问题,谢谢所有能给我线索的人!

【问题讨论】:

  • 什么是月经箱线图?你是说每月吗?
  • 是的,对不起,我的意思是每月

标签: pandas datetime matplotlib seaborn boxplot


【解决方案1】:

您可以添加带有月份的列(使用df.index.month),然后使用DataFrame.boxplotcolumn='ex1'by='month' 参数绘制它:

# generate some data
N = 365
df=pd.DataFrame({
    'date': pd.date_range('2021-01-01', periods=N),
    'ex1': np.random.random(N) * range(N),
    'ex2': np.random.random(N),
    'ex3': np.random.random(N),
})
df['date']=pd.to_datetime(df['date'])
df=df.set_index(['date'])

# plot
df.assign(month=df.index.month).boxplot(
    column='ex1', by='month', figsize=(12, 6))

输出:

或者如果你想用seaborn + 使用index.month_name() 来显示月份名称而不是数字:

fig, ax = plt.subplots(figsize=(12, 6))
sns.boxplot(
    x='month', y='ex1',
    data=df.assign(month=df.index.month_name()),
    ax=ax)

输出:

【讨论】:

  • 这太简单了,我很惭愧我自己没有找到它......非常感谢!
  • @SonnePer 如果您愿意,请考虑accepting 的答案,以向其他人表明问题已解决。
猜你喜欢
  • 2017-10-04
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 2020-08-29
  • 2021-09-30
相关资源
最近更新 更多