【问题标题】:Return the consecutive missing weekdays dates and assign rate next to missing dates返回连续缺失的工作日日期并在缺失日期旁边分配费率
【发布时间】:2020-02-11 09:49:03
【问题描述】:
Dates       rates
7/26/2019   1.04
7/30/2019   1.0116
7/31/2019   1.005
8/1/2019    1.035
8/2/2019    1.01
8/6/2019    0.9886
8/12/2019   0.965

df = df.merge(
    pd.DataFrame({'Dates':df['Dates'] + pd.offsets.BDay()}), on='Dates', how='outer'
).sort_values('Dates').bfill().dropna().reset_index(drop=True)

print(df)

我尝试了上述代码,但无法修复连续缺失的工作日。它只能修复1天。在上述数据框中,缺少 2019 年 7 月 29 日和 8 月 5 日、7 日、8 日、9 日。这些是工作日。我需要填充缺失的工作日日期并分配缺失日期旁边的“费率”。例如:将 2019 年 7 月 30 日的“汇率”分配给缺失的 2019 年 7 月 29 日,依此类推,用于所有缺失的日期。请建议。谢谢,我期待以下输出

Dates       rates
7/26/2019   1.04
7/29/2019   1.021
7/30/2019   1.0116
7/31/2019   1.005
8/1/2019    1.035
8/2/2019    1.01
8/5/2019    0.9886
8/6/2019    0.9886
8/7/2019    0.965
8/8/2019    0.965
8/8/2019    0.965
8/12/2019   0.965

【问题讨论】:

  • 这项工作df.set_index('Dates').asfreq('B').ffill()
  • 请详细说明。我试过但没用。
  • 您没有描述您认为最终结果应该是什么样子。因此,我不想花时间创建一个关于什么是猜测的答案(包括更多详细说明)。它没有用。那说明我猜错了。如果没有实际的minimal reproducible example,我会继续前进。
  • 我已经这样做了 df = df.merge(pd.DataFrame({'Date':df['Date'] + pd.offsets.BDay()}), on='Date' , how='outer').set_index('Date').asfreq('B').ffill().sort_values('Date') 并得到 TypeError: must be str, not BusinessDay
  • 我想看看你最终的期望,除了你已经尝试过的。此外,提供生成数据框的代码也会很有帮助。正如您所拥有的,我无法判断您的 'Dates' 列实际上是日期还是看起来像日期的字符串。

标签: python pandas


【解决方案1】:

尝试下面的选项 1,其中包括创建新的 df 并合并它(您已经在的路线)

或@piRSquared 建议的选项 2(bfill() 而不是 ffill()

df['Dates'] = pd.to_datetime(df['Dates'])
a=pd.DataFrame({'Dates':pd.bdate_range('2019-07-26', '2019-08-12')})
df.merge(a, on='Dates', how='outer').sort_values('Dates').bfill().dropna().reset_index(drop=True) 

输出

        Dates   rates
0   2019-07-26  1.0400
1   2019-07-29  1.0116
2   2019-07-30  1.0116
3   2019-07-31  1.0050
4   2019-08-01  1.0350
5   2019-08-02  1.0100
6   2019-08-05  0.9886
7   2019-08-06  0.9886
8   2019-08-07  0.9650
9   2019-08-08  0.9650
10  2019-08-09  0.9650
11  2019-08-12  0.9650
df.set_index('Dates').asfreq('B').bfill().reset_index()

输出

         Dates  rates
0   2019-07-26  1.0400
1   2019-07-29  1.0116
2   2019-07-30  1.0116
3   2019-07-31  1.0050
4   2019-08-01  1.0350
5   2019-08-02  1.0100
6   2019-08-05  0.9886
7   2019-08-06  0.9886
8   2019-08-07  0.9650
9   2019-08-08  0.9650
10  2019-08-09  0.9650
11  2019-08-12  0.9650

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多