gpt4 book ai didi

python - 无法计算两个日期之间的工作日?将 dtype ('
转载 作者:太空宇宙 更新时间:2023-11-03 20:05:01 24 4
gpt4 key购买 nike

我希望计算两个日期之间的工作日(不包括星期日和星期六),一个在数据框列内,另一个是今天的当前日期,但出现错误:

REF8_df['Days_Dif'] = np.busday_count(REF8_df['Session1_Date'], Todays_Date)
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'

我的代码:

df = Main_Database['Session1_Date']
Todays_Date = np.datetime64('today', dtype='datetime64[D]')
df['Session1_Date'] = df['Session1_Date'].values.astype('datetime64[D]')
df['Days_Difference'] = np.busday_count(df['Session1_Date'], Todays_Date)

我很困惑为什么这不起作用?

最佳答案

问题可能会出现,因为数据框和系列仅将类似日期时间的对象保存为 dtype datetime64[ns] 的对象。因此这一行:

df['Session1_Date'] = df['Session1_Date'].values.astype('datetime64[D]')

不存储您想要实现的到 .datetime64[D] 的转换。下面的解决方案有效。

import datetime
import pandas as pd
import numpy as np

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

var_1 = np.random.sample(dates.size)
df = pd.DataFrame(data={'Var_1': var_1, 'Session1_Date': dates})
df = df[['Session1_Date', 'Var_1']]
df.head()

# Calculate today's date and convert to 'M8[D]'
Todays_Date = np.datetime64('today')

# Calculate the business days
df['Days_Difference'] = np.busday_count(df['Session1_Date'].values.astype('M8[D]'), Todays_Date)

df.head()

输出

df.head() # Original data frame
Out[89]:
Session1_Date Var_1
0 2019-04-05 0.625200
1 2019-04-06 0.482555
2 2019-04-07 0.701814
3 2019-04-08 0.876485
4 2019-04-09 0.117023

df.head() # With computed business days
Out[90]:
Session1_Date Var_1 Days_Difference
0 2019-04-05 0.625200 166
1 2019-04-06 0.482555 165
2 2019-04-07 0.701814 165
3 2019-04-08 0.876485 165
4 2019-04-09 0.117023 164

关于python - 无法计算两个日期之间的工作日?将 dtype ('<M8[ns]' ) 转换为 dtype ('<M8[D]' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016802/

24 4 0

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com