使用 Grouper 的 pandas 系列日期时间索引中的月份名称

问题描述 投票:0回答:2

我正在将一年的数据(六月至五月)按月绘制成胡须箱图。

我有 pandas 系列的数据:

Date
2018-06-01    0.012997
2018-06-02    0.009615
2018-06-03    0.012884
2018-06-04    0.013358
2018-06-05    0.013322
2018-06-06    0.011532
2018-06-07    0.018297
2018-06-08    0.018820
2018-06-09    0.031254
2018-06-10    0.016529
...
Name: Value, dtype: float64

我可以绘制它,但我无法获取月份名称列,因此它只是用数字绘制的。然而,由于月份不是从 Jan = Dec 开始,因此月份数字没有意义。

当我使用 Grouper 函数创建这样的 df 时,有什么方法可以获取月份名称吗?

我使用的代码最初来自https://machinelearningmastery.com/time-series-data-visualization-with-python/

如果我理解正确的话,石斑鱼将系列排列成一个包含每月数据的数组,所以我想这就是可能的点(如果有的话):

groups = series.groupby(pd.Grouper(freq = 'M'))
months = pd.concat([pd.DataFrame(x[1].values) for x in groups], axis=1)

我尝试查找但无法获得有关使用 pd.DataFrame 函数时如何根据任何条件命名列的任何提示。如果有人能帮助我找到正确的方向,我将非常感激。

fig = plt.figure(figsize = (16,8))

#some code for other plots

ax3 = fig.add_subplot(212)
groups = series.groupby(pd.Grouper(freq = 'M'))
months = pd.concat([pd.DataFrame(x[1].values) for x in groups], axis=1)
months = pd.DataFrame(months)
months.columns = range(1,13)
months.boxplot()
ax3.set_title('Results June 2018 - May 2019')

plt.show()
python-3.x pandas time-series pandas-groupby
2个回答
1
投票

您可以使用

strftime
函数和
'%B'
转换字符串来获取相应的月份名称,然后绘制它们。

这是一些示例代码:

series = pd.Series({'2018-06-01':0.012997,
'2018-06-02':0.009615,
'2018-07-03':0.012884,
'2018-06-04':0.013358,
'2018-08-05':0.013322,
'2018-09-06':0.011532,
'2018-10-07':0.018297,
'2018-11-08':0.018820,
'2018-12-09':0.031254,
'2018-06-10':0.016529})

series.index = pd.to_datetime(series.index)

fig = plt.figure(figsize = (16,8))

ax3 = fig.add_subplot(212)
group = series.groupby(pd.Grouper(freq = 'M')).sum()
plt.bar(group.index.strftime('%B'), group)

ax3.set_title('Results June 2018 - May 2019')

plt.show()

这是它生成的相应图:


0
投票

与@Jairo 相同,但使用 df。

index = [
'2018-06-01',
'2018-06-02',
'2018-07-03',
'2018-06-04',
'2018-08-05',
'2018-09-06',
'2018-10-07',
'2018-11-08',
'2018-12-09',
'2018-06-10'
]

data = [
0.012997,
0.009615,
0.012884,
0.013358,
0.013322,
0.011532,
0.018297,
0.018820,
0.031254,
0.016529
]

df = pd.DataFrame(data, index=index)
df.index = pd.to_datetime(df.index)

fig = plt.figure(figsize = (16,8))

ax3 = fig.add_subplot(212)
group = df.groupby(pd.Grouper(freq = 'M')).sum()
plt.bar(group.index.strftime('%B'), group[0])

ax3.set_title('Results June 2018 - May 2019')
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.