【问题标题】:Python Business Days within loop循环内的 Python 工作日
【发布时间】:2019-12-12 15:04:00
【问题描述】:

我正在尝试遍历数据框,该数据框有两列,其中都有日期时间变量。我正在尝试遍历此数据库并生成一个新列,其中包含两个日期之间的工作日数。我尝试使用 np.busdays_count

df_Temp['Maturity(Stlm -Report Date)'] = np.busday_count(df_Temp['Today'],df_Temp['STLMT_DTE2'])


Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in busday_count
TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[ns]') to dtype('<M8[D]') according to the rule 'safe'

我也尝试过使用以下功能:

import datetime

def working_days(start_dt,end_dt):
    num_days = (end_dt -start_dt).days +1
    num_weeks =(num_days)//7
    a=0
    #condition 1
    if end_dt.strftime('%a')=='Sat':
        if start_dt.strftime('%a') != 'Sun':
            a= 1
    #condition 2
    if start_dt.strftime('%a')=='Sun':
        if end_dt.strftime('%a') !='Sat':
            a =1
    #condition 3
    if end_dt.strftime('%a')=='Sun':
        if start_dt.strftime('%a') not in ('Mon','Sun'):
            a =2
    #condition 4        
    if start_dt.weekday() not in (0,6):
        if (start_dt.weekday() -end_dt.weekday()) >=2:
            a =2
    working_days =num_days -(num_weeks*2)-a

    return working_days

请您建议使用另一种方法或对工作日功能进行调整以使其正常工作,到目前为止,我有以下代码。我希望我能详细介绍这一点。

for ns in (NettingSets):

    df_Temp = dfNetY[dfNetY['ACCT_NUM'] == ns]
    df_Temp['Current Credit Exposure'] = np.where(df_Temp['All NPV Flags']==1,0,df_Temp['MTM_AMT'])
    df_Temp['Positive Current Credit Exposure'] = np.where(df_Temp['Current Credit Exposure'] > 0,df_Temp['Current Credit Exposure'],0)
    df_Temp['SupervisoryFactor'] = 0.04
    df_Temp['STLMT_DTE2'] = pd.to_datetime(df_Temp['STLMT_DTE2'].astype(str), format='%Y-%m-%d')
    df_Temp['Today'] = date1
    df_Temp['Today'] = pd.to_datetime(df_Temp['Today'].astype(str), format='%Y-%m-%d')

for rows in df_Temp:
    df_Temp['Maturity(Stlm -Report Date)'] = np.busday_count(df_Temp['Today'],df_Temp['STLMT_DTE2'])

【问题讨论】:

  • 为什么要循环播放?只需 df_Temp['Maturity(Stlm -Report Date)'] = df_Temp['Today'] - df_Temp['STLMT_DTE2'] 这将适用于每一行?
  • 欢迎来到 StackOverflow。请阅读How to ask,并发布Minimal, Complete, Verifiable Example。另外,不要说“它不起作用”,而是告诉我们当你使用 np.busdays_cout 时会发生什么。但绝对发布一个 MVCE。这是在这里获得快速帮助的最佳方式!
  • 嗨,Datanovice,效果很好,这是我试图只计算工作日的事实,但是使用 np.busdays_count 仅在不在系列中时才有效。所以我试图找到一种可以计算 df_Temp['Today'] 和 df_Temp['STLMT_DTE2'] 之间的工作日。有多行的地方。希望能更清楚
  • 不要担心投反对票 - 但请理解,如果没有样本量的数据并且您的预期输出(必须是文本)阅读 Jeff 的链接和然后重新编辑您的问题。一旦你这样做,我会尽力而为。
  • 您需要正确格式化两个日期,然后这应该可以解决问题:stackoverflow.com/a/59272172/11610186

标签: python pandas datetime weekend


【解决方案1】:

为了使 np.busday_count 起作用,两个日期都需要以“M8[D]”格式进行转换。

import datetime
import pandas as pd
import numpy as np

# Create a toy data frame
dates_1 = pd.date_range(datetime.datetime(2018, 4, 5, 0, 
                      0), datetime.datetime(2018, 4, 20, 7, 0),freq='D')

dates_2 = pd.date_range(datetime.datetime(2019, 4, 5, 0, 
                      0), datetime.datetime(2019, 4, 20, 7, 0),freq='D')

df_Temp = pd.DataFrame({'STLMT_DTE2': dates_1, 'Today': dates_2})
df_Temp.head()

df_Temp['Maturity(Stlm-Report Date)'] = np.abs(
        np.busday_count(df_Temp['Today'].values.astype('M8[D]'),
                        df_Temp['STLMT_DTE2'].values.astype('M8[D]')))

df_Temp.head()

输出:

df_Temp.head()
Out[16]: # Before calculating business days
  STLMT_DTE2      Today
0 2018-04-05 2019-04-05
1 2018-04-06 2019-04-06
2 2018-04-07 2019-04-07
3 2018-04-08 2019-04-08
4 2018-04-09 2019-04-09

df_Temp.head()
Out[17]: # After calculating business days
  STLMT_DTE2      Today  Maturity(Stlm-Report Date)
0 2018-04-05 2019-04-05                         261
1 2018-04-06 2019-04-06                         261
2 2018-04-07 2019-04-07                         260
3 2018-04-08 2019-04-08                         260
4 2018-04-09 2019-04-09                         261

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    相关资源
    最近更新 更多