我正在尝试按月DataFrame
分组进行绘图,其中索引列是DateTime
。
我的目标是将所有月份绘制在单独的图上。
index=date_range('2011-9-1 00:00:03', '2012-09-01 00:00:03', freq='10min')
df=pd.DataFrame(np.random.rand(len(index),3),index=index)
df2 = df.groupby(lambda x: x.month)
df2.plot()
这给了我 14 个图(不是 12 个),其中前 2 个是空的 - x 轴上是从 2000 年到 2010 年的年份。前两个图是 1 月。
希望您能提供如何应对此问题的好建议。
最佳答案
你想要实现什么目标?对数据进行分组时,如果您想绘制数据,通常会以某种方式对其进行聚合。例如:
import pandas as pd
index=pd.date_range('2011-1-1 00:00:03', '2011-12-31 23:50:03', freq='10min')
df=pd.DataFrame(np.random.rand(len(index),3),index=index)
df2 = df.groupby(lambda x: x.month)
for key, group in df2:
group.plot()
更新:修复了跨度超过一个月的群组。这可能不是最好的解决方案,但这是我首先想到的解决方案。
import pandas as pd
num_ticks = 15
index=pd.date_range('2011-9-1 00:00:03', '2012-09-01 00:00:03', freq='10min')
df=pd.DataFrame(np.random.rand(len(index),3),index=index)
df2 = df.groupby(lambda x: x.month)
for key, group in df2:
step = len(group) / num_ticks
reset = group.reset_index()
reset.plot()
plt.xticks(reset.index[::step],
reset['index'][::step].apply(
lambda x: x.strftime('%Y-%m-%d')).values,
rotation=70)
关于python - 按月绘制 groupby 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452007/