python - 在 Pandas 中,从具有年和周的多索引生成日期时间索引

标签 python datetime pandas

我有一个 DataFrame df带列saledate (在 DateTime 中,dytpe <M8[ns] )和 price (dytpe int64 ),如果我像这样绘制它们

fig, ax = plt.subplots()
ax.plot_date(dfp['saledate'],dfp['price']/1000.0,'.')
ax.set_xlabel('Date of sale')
ax.set_ylabel('Price (1,000 euros)')

我得到一个如下所示的散点图。

enter image description here

由于点太多,很难辨别平均趋势,因此我想计算每周的平均销售价格,并将其绘制在同一个图中。我尝试过以下方法:

dfp_week = dfp.groupby([dfp['saledate'].dt.year, dfp['saledate'].dt.week]).mean()

如果我像这样绘制结果“价格”列

plt.figure()
plt.plot(df_week['price'].values/1000.0)
plt.ylabel('Price (1,000 euros)')

我可以更清楚地辨别出增长趋势(见下文)。

enter image description here

问题是我不再有时间轴来在与上图相同的图中绘制此数据系列。时间轴是这样开始的:

                   longitude_4pp  postal_code_4pp     price  rooms  \
saledate saledate                                                    
2014     1              4.873140           1067.5  206250.0    2.5   
         6              4.954779           1102.0  129000.0    3.0   
         26             4.938828           1019.0  327500.0    3.0   
         40             4.896904           1073.0  249000.0    2.0   
         43             4.938828           1019.0  549000.0    5.0 

如何将这个包含年和周的多索引转换回单个日期时间索引,以便我可以根据该索引绘制每周平均数据?

最佳答案

如果您使用 pd.TimeGrouper 进行分组,您将在索引中保留日期时间。

dfp.groupby(pd.TimeGrouper('W')).mean()

关于python - 在 Pandas 中,从具有年和周的多索引生成日期时间索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38462214/

相关文章:

python - 无法在 Linux Manjaro 上运行 Spyder

python - 使用 Beautiful Soup 提取 css 链接

python - 用于计算正态分布标准偏差的标准 C 或 Python 库

c# - 为什么不 DateTime.ToString ("R") 和 DateTime.TryParseExact 往返?

python - 按 multiIndex 之一的最高分位数过滤数据帧行

Python pandas 数据框将函数结果应用于多列,其中 NaN

python - 结合 Pandas 的 startwith 和 isin

python - 两个正态分布与scipy的重叠概率

c# - 将波斯日期转换为标准英文日期

python - 为什么 `datetime.strptime` 得到的 2015 年第 0 周星期二的日期不正确?