我有一组日期时间对象 x 和一组与这些日期时间对应的 y 值。我正在尝试创建一个直方图,该直方图按月将所有这些 y 值分组到同一个 bin 中。基本上是将同一个月内的所有 y 值相加,并创建一个直方图来显示每个月的总值。
这是我的数据的简化版本:
x = np.array(datetime.datetime(2014, 2, 1, 0, 0), datetime.datetime(2014, 2, 13, 0, 0),\n
datetime.datetime(2014, 3, 4, 0, 0), datetime.datetime(2014, 3, 6, 0, 0))
y = np.array(4,3,2,6)
最终结果应该是一个直方图,显示 2014 年第 2 个月的 y 值 7 和 2014 年第 3 个月的 y 值 8。
我尝试的第一件事是从我的两个数组中创建一个 pandas 数据框,如下所示:
frame = pd.DataFrame({'x':x,'y':y})
这适用于 x 映射到所有日期时间对象和 y 映射到所有对应值。但是,在创建此数据框之后,我有点迷失了如何按月添加所有 y 值并使用 plt.hist() 在这些月中创建 bin
最佳答案
首先,感谢您提出一个带有数据示例的恰当问题。
这似乎是你想要的:
import pandas as pd
import numpy as np
import datetime
%matplotlib inline
x = np.array([datetime.datetime(2014, 2, 1, 0, 0),
datetime.datetime(2014, 2, 13, 0, 0),
datetime.datetime(2014, 3, 4, 0, 0),
datetime.datetime(2014, 3, 6, 0, 0)])
y = np.array([4,3,2,6])
frame = pd.DataFrame({'x':x,'y':y})
(frame.set_index('x'). # use date-time as index
assign(month=lambda x: x.index.month). # add new column with month
groupby('month'). # group by that column
sum(). # find a sum of the only column 'y'
plot.bar()) # make a barplot
关于python - 来自 x、y 值的 Matplotlib 直方图,日期时间月份作为 bin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309843/