【问题标题】:Business days between two dates in PythonPython中两个日期之间的工作日
【发布时间】:2023-03-09 11:10:02
【问题描述】:

我在数据框中有两列 "Blk Start""Blk End"。我需要通过计算两个日期之间的工作日数来创建第三列。我正在使用下面的代码,但它不起作用

df[x] = np.busday_count(df['Blk_start'],df['Blk_end'])

我还需要使用其他功能吗?

上面代码的错误是:

TypeError Traceback (最近一次调用最后一次) in ----> 1 df[x] = np.busday_count(df['Blk_start'],df['Blk_end']) TypeError: Iterator operand 0 dtype could not be根据“安全”规则从dtype('<M8[ns]') 转换为dtype('<M8[D]')

列格式为:

fundmgr_id   int64 
user_name    object 
Blk_start.   datetime64[ns] 
Blk_end      datetime64[ns] 

【问题讨论】:

  • 您能否分享您获得的错误代码或解释您的数据框的外观。从 numpy 签出 docs,看看你是否可以通过一个简单的例子让它工作。它可能与这些列中数据的格式有关,或者您必须循环应用数据框才能使其工作。
  • df[x] = np.busday_count(df['Blk_start'],df['Blk_end']) df[x] = np.busday_count(df['Blk_start'],df[' Blk_end']) ---------------------------------------------- ----------------------------- TypeError Traceback (最近一次调用最后一次) in ----> 1 df[x] = np.busday_count(df['Blk_start'],df['Blk_end']) TypeError: Iterator operand 0 dtype could not be cast from dtype('
  • fundmgr_id int64 user_name object Blk_start datetime64[ns] Blk_end datetime64[ns]
  • 以后,请通过编辑问题添加其他信息,而不是作为 cmets。

标签: python pandas numpy date multiple-columns


【解决方案1】:

np.busday_count 表示它适用于 类似 datetime64[D] 的数组,因此您可以先将列转换为该格式,然后再执行操作。

en = df["Blk_end"].values.astype('datetime64[D]')
st = df["Blk_start"].values.astype('datetime64[D]')
df["x"] = np.busday_count(st, en)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2020-11-20
    • 2010-09-20
    相关资源
    最近更新 更多