【问题标题】:Datetime in PandasPandas 中的日期时间
【发布时间】:2020-12-02 11:57:32
【问题描述】:

我有一个类似于以下的数据框:

--------------------------------------------------------------------------------------
| Start_Date       |  End_Date         | Jan-16 | Feb-16 | Mar-16 | Apr-16 | May-16   |
| 2016-02-20 17:40 |  2019-11-20 16:31 |  0     | 1      | 1      | 1      | 1        |
| 2016-03-11 15:12 |  2020-11-01 12:12 |  0     | 0      | 1      | 1      | 1        |
---------------------------------------------------------------------------------------

如果开始和结束日期介于 2016 年 1 月至 2020 年 12 月之间,我需要使用 PANDAS 在相应的月份列中输入 1 或 0。例如,在第一行中,日期为 2020 年 2 月 20 日。因此,1 月 16 日列中有 0,2 月 16 日、3 月 16 日、16 年 4 月等列中有 1。 日期采用年月日格式。

你是如何做到这一点的?

【问题讨论】:

  • np.where((df['Start_Date'] > '01 Jan 2016') & (df['End_Date'] < '31 Dec 2020'), 1,0) ?
  • 这里不需要导入numpydf['in_range'] = ((df['Start_Date'] > '2016-01') & (df['End_Date'] <= '2020-12')).astype(int) 可以。只需确保将日期列转换为日期时间。
  • 感谢您的回复,但这不是我需要的。抱歉,我刚刚更新了问题以便更清楚地理解。我需要在每个月列中使用 0 和 1。这个问题你还能帮我解决吗?
  • 所以你有 2016 年 1 月到 2020 年 12 月之间每个月的列,即 5 年 X 12 个月的 60 列?
  • 是的,我有专栏

标签: python pandas dataframe datetime python-datetime


【解决方案1】:

如果您要计算开始日期和结束日期之间的月份数,

import datetime
start_date = datetime.datetime.strptime('2016-02-20 17:40', '%Y-%m-%d %H:%M')
end_date = datetime.datetime.strptime('2019-11-20 16:31', '%Y-%m-%d %H:%M')
num_months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)

num_months 打印(num_months)

【讨论】:

    猜你喜欢
    • 2018-08-13
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2014-09-18
    • 1970-01-01
    • 2022-11-22
    • 2021-11-04
    相关资源
    最近更新 更多