【问题标题】:Count of the total number of rows meeting a specific condition between two different dates of another DataFrame在另一个 DataFrame 的两个不同日期之间满足特定条件的总行数
【发布时间】:2022-10-07 17:36:03
【问题描述】:

成为以下 python pandas DataFrame:

| num_ID | start_date  | end_date   | time              |
| ------ | ----------- | ---------- | ----------------- |
| 1      | 2022-02-14  | 2022-02-15 | 0 days 09:23:00   |
| 2      | 2022-02-12  | 2022-02-15 | 2 days 10:23:00   |
| 2      | 2022-02-05  | 2022-02-27 | 22 days 02:35:00  |
| 3      | 2022-02-04  | 2022-02-06 | 1 days 19:55:00   |

以下 DataFrame 在is_holiday 列中包含连续日期及其各自的假期值。

| date       | is_holiday | name | other |
| ---------- | ---------- | ---- | ----- |
| 2022-01-01 | True       | ABC  | red   |
| 2022-01-02 | False      | CNA  | blue  |
...
# we assume in this case that the omitted rows have the value False in column 
| 2022-02-15 | True       | OOO  | red   |
| 2022-02-16 | True       | POO  | red   |
| 2022-02-17 | False      | KTY  | blue  |
...
| 2023-12-30 | False      | TTE  | white |
| 2023-12-31 | True       | VVV  | red   |

我想在初始 DataFrame 中添加一个新列 total_days,它指示在第二个 DataFrame 中标记为 True 的总假期,每行在两个日期之间传递(start_dateend_date)。

输出结果示例:

| num_ID | start_date  | end_date   | time              | total_days     |
| ------ | ----------- | ---------- | ----------------- | -------------- |
| 1      | 2022-02-14  | 2022-02-15 | 0 days 09:23:00   | 1              |
| 2      | 2022-02-12  | 2022-02-15 | 2 days 10:23:00   | 1              |
| 2      | 2022-02-05  | 2022-02-27 | 22 days 02:35:00  | 2              |
| 3      | 2022-02-04  | 2022-02-06 | 1 days 19:55:00   | 0              |

    标签: python pandas dataframe datetime


    【解决方案1】:

    利用:

    df2 = df.merge(df1.loc[df1['holiday'], ['date']], how='cross')
    s = (df2[df2['date'].between(df2["start_date"],df2["end_date"])]
           .groupby(['start_date','end_date']).size())
    
    df = (df.join(s.rename('total_holidays'), on=['start_date','end_date'])
           .fillna({'total_holidays':0}))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      相关资源
      最近更新 更多