How to plot kernel density plot of dates in Pandas?(如何在 Pandas 中绘制日期的核密度图?)
问题描述
我有一个 pandas 数据框,其中每个观察值都有一个日期(作为 datetime[64] 格式的条目列).这些日期分布在大约 5 年的时间里.我想绘制所有观察日期的核密度图,年份标记在 x 轴上.
I have a pandas dataframe where each observation has a date (as a column of entries in datetime[64] format). These dates are spread over a period of about 5 years. I would like to plot a kernel-density plot of the dates of all the observations, with the years labelled on the x-axis.
我已经弄清楚如何创建一个相对于某个参考日期的时间增量,然后创建一个每次观察与参考日期之间的小时数/天数/年数的密度图:
I have figured out how to create a time-delta relative to some reference date and then create a density plot of the number of hours/days/years between each observation and the reference date:
但这并不是我想要的:如果我转换为年份增量,那么 x 轴是正确的,但我失去了年内变化.但是,如果我使用较小的时间单位,例如小时或天,x 轴标签就更难解释了.
But this isn't exactly what I want: If I convert to year-deltas, then the x-axis is right but I lose the within-year variation. But if I take a smaller unit of time like hour or day, the x-axis labels are much harder to interpret.
在 Pandas 中进行这项工作的最简单方法是什么?
What's the simplest way to make this work in Pandas?
推荐答案
受@JohnE 回答的启发,将日期转换为数值的另一种方法是使用 .toordinal()
.
Inspired by @JohnE 's answer, an alternative approach to convert date to numeric value is to use .toordinal()
.
这篇关于如何在 Pandas 中绘制日期的核密度图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!