【问题标题】:Keeping the first day of the month in a timestamp object将每月的第一天保存在时间戳对象中
【发布时间】:2021-09-20 21:17:02
【问题描述】:

我有一个包含一年中所有日期的时间戳列的 DataFrame。

我想只保留本月的第一天,知道该怎么做吗?

【问题讨论】:

标签: python pandas time-series timestamp


【解决方案1】:

请参阅这篇文章,了解如何在 Stack Overflow 上提出一个好的问题并提供一个可重复的最小示例:

https://stackoverflow.com/help/how-to-ask

考虑到这一点,您可以访问 datetime 对象的 day 属性,如下所示:

from datetime import datetime

dt = datetime.today()
dt.day

输出:

2021-07-11 09:37:23.122548
11

然后,您可以使用掩码来选择数据框中的值为 1 的行,如下所示:

df = df[df['date_column'].dt.day == 1]

您只需将“date_column”替换为您调用的日期列。

我们的网站上有一个完整介绍熊猫的教程,如果您想了解更多信息,请随时查看!

https://www.learndatasci.com/tutorials/python-pandas-tutorial-complete-introduction-for-beginners/

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 2014-03-18
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多