【问题标题】:Python: can I convert a datetime to a float with granularity lesser than a whole day?Python:我可以将日期时间转换为粒度小于一整天的浮点数吗?
【发布时间】:2021-09-29 22:57:33
【问题描述】:

我正在尝试绘制血压读数,每个读数都有一个日期时间时间戳,其中包含读数的日期和小时:分钟:秒。

由于许多 Seaborn 回归图(lmplot、regplot 等)不支持日期时间时间戳,因此我使用如下数字序数创建了一个新的数据框列:

from datetime import date
df['date_ordinal'] = pd.to_datetime(df['date']).apply(lambda date: date.toordinal())

这可行,但问题是在同一天获取的多个读数都堆叠在同一个 x 轴点上。

有没有比序号更好的函数来实现将同一天的读数与序号后的十进制值分开?

【问题讨论】:

  • 这是您所期待的吗? stackoverflow.com/questions/48860428/…
  • 没有。该帖子告诉您如何使用日期时间值在 x 轴上绘制值,该帖子不支持该值。我解决了这个问题,使用 toordinal() 函数将日期时间时间戳转换为整数(从 1970 年 1 月 1 日开始的天数),但这给出了一个整数,并丢弃了 h:mm:ss 部分

标签: python dataframe datetime seaborn


【解决方案1】:

您可以计算date 列中每个datetime 与最旧datetime 之间的timedeltas,然后使用timedelta 的秒数。这意味着计算自最早时间戳以来的相对时间(以秒为单位):

df['seconds_since_start'] = df['date'].apply(lambda date: (date - df['date'].min()).seconds)

从这里,您可以使用基本数学将秒转换为天(使用十进制值):

df['days_since_start'] = df['seconds_since_start'] / (60 * 60 * 24)

【讨论】:

  • 你可能想要.total_seconds()而不是.seconds
【解决方案2】:

感谢@jfaccioni 提示正确的方向:) 这就是我所做的。

首先将一个日期时间对象转换为一个浮点数,以便它可以被seaborn的散点图使用。

我使用时间戳函数将日期时间转换为纪元(从 1970 年 1 月 1 日开始的秒数):

df['date_ordinal'] = pd.to_datetime(df['Measurement Date']).apply(lambda date: date.timestamp())

我已经解决了我的需求。只是为了帮助有类似要求的人,这是第二部分。

如何将那些大秒数转换回日期字符串,以便它们可以用作我的 seaborn x 轴图的标签:

# now convert the epoch values back to a YYYY-MM-DD string for the x labels
# localtime converts the epoch into a datetime object abd strftime converts it into a string
new_labels = [time.strftime('%Y-%m-%d',time.localtime(item)) for item in ax.get_xticks()]
ax.set_xticklabels(new_labels)

【讨论】:

    猜你喜欢
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2022-11-15
    • 2022-01-17
    相关资源
    最近更新 更多