【问题标题】:Changing selective index dates in pandas更改 pandas 中的选择性索引日期
【发布时间】:2020-07-04 21:41:04
【问题描述】:

我有一个日期列表:

xl_file

                     Day
Date                 
2011-01-26  Wednesday
2011-03-02  Wednesday
2011-04-12    Tuesday
2011-04-14   Thursday
2011-04-22     Friday
              ...
2020-05-25     Monday
2020-10-02     Friday
2020-11-16     Monday
2020-11-30     Monday
2020-12-25     Friday

[144 rows x 1 columns]

在上面数据框中列出的日期中,这些是我需要更改的日期:

list_of_dates

Empty DataFrame
Columns: []
Index: [2018-01-25 00:00:00, 2018-02-22 00:00:00, 2018-04-26 00:00:00, 2018-05-31 00:00:00, 2018-06-28 00:00:00, 2018-07-26 00:00:00, 2018-08-30 00:00:00, 2018-09-27 00:00:00, 2018-10-25 00:00:00, 2018-11-29 00:00:00, 2018-12-27 00:00:00, 2019-01-31 00:00:00, 2019-02-28 00:00:00, 2019-03-28 00:00:00, 2019-04-25 00:00:00, 2019-05-30 00:00:00, 2019-06-27 00:00:00, 2019-07-25 00:00:00, 2019-08-29 00:00:00, 2019-09-26 00:00:00, 2019-10-31 00:00:00, 2019-11-28 00:00:00, 2019-12-26 00:00:00, 2020-01-30 00:00:00, 2020-02-27 00:00:00, 2020-03-26 00:00:00, 2020-04-30 00:00:00, 2020-05-28 00:00:00, 2020-06-25 00:00:00]

我想要做的是日期出现在 xl_file 的数据框 list_of_dates 中的任何位置,Date 更改为:

list_of_dates.index + BDay()

但是,该行的内容保持不变。

例如,如果xl_file 中的日期是

2020-06-25    Thursday 

该日期也在list_of_dates 中,因此应该将日期更改为下一个BDay(),即:

2020-06-26    Thursday 

不更改该行其余部分的条目。我该怎么做?

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    您可以执行以下操作:

    xl_file["Date"] = xl_file["Date"].apply(lambda x: x + BDay() if x in list_of_dates.index else x)
    

    编辑:刚刚注意到这是您正在调整的索引,所以您可以这样做:

    xl_file.index = xl_file.index.map(lambda x: x + BDay() if x in list_of_dates.index else x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 2019-08-23
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多