简体   繁体   English

查找包含 NaT 的 Pandas 数据框中两列之间的工作日

[英]Find the business days between two columns in a pandas dataframe, which contain NaTs

I have 2 columns in my pandas data frame, and I want to calculate the business dates between them.我的 Pandas 数据框中有 2 列,我想计算它们之间的营业日期。

Data:数据:

 ID     On hold     Off Hold
 101    09/15/2017  09/16/2017
 102    NA          NA
 103    09/22/2017  09/26/2017
 104    10/12/2017  10/30/2017
 105    NA          NA
 106    08/05/2017  08/06/2017
 107    08/08/2017  08/03/2017
 108    NA          NA

I tried the below code using busday_count from numpy:我使用 numpy 中的 busday_count 尝试了以下代码:

 df1['On hold'] = pd.to_datetime(df1['On hold'])
 df1['Off Hold'] = pd.to_datetime(df1['Off Hold'])
 np.busday_count(df1['On hold'].values.astype('datetime64[D]'),df1['Off Hold'].values.astype('datetime64[D]'))

also,还,

 np.where(pd.notnull(df1['On hold']),np.busday_count(df1['On hold'].values.astype('datetime64[D]'),
                                                df1['Off Hold'].values.astype('datetime64[D]')),0)

The error was :错误是:

   Cannot compute a business day count with a NaT (not-a-time) date

Any help will be appreciated :)任何帮助将不胜感激 :)

使用pd.bdate_range方法:

pd.bdate_range(df['On Hold'], df['Off Hold'], freq = 'B')

You can try the below:您可以尝试以下方法:

f = df1.dropna()
f['days'] = np.busday_count(pd.to_datetime(f['On hold']).values.astype('datetime64[D]'), \
            pd.to_datetime(f['Off hold']).values.astype('datetime64[D]'))

df1.merge(f[['ID', 'days']],on='ID', how='left')

Try to drop NA first before you do bus day count.在计算公交车天数之前,请先尝试删除 NA。 You can drop all the NA by using the following.您可以使用以下命令删除所有 NA。

new_df = df.dropna()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM