簡體   English   中英

如何用 python 計算工作日數

[英]how to calculate number of working days with python

我有一個 dataframe(df):

    year  month ETP
0   2021    1   49.21
1   2021    2   34.20
2   2021    3   31.27
3   2021    4   29.18
4   2021    5   33.25
5   2021    6   24.70

我想添加一列,為我提供每行的工作日數,不包括節假日和周末(對於特定國家,exp:法國或美國)

所以 output 將是:

    year  month ETP     work_day
0   2021    1   49.21      20
1   2021    2   34.20      20
2   2021    3   31.27      21
3   2021    4   29.18      19
4   2021    5   33.25      20
5   2021    6   24.70      19

代碼:

import numpy as np
import pandas as pd
days = np.busday_count( '2021-01', '2021-06' ) 
df.insert(3, "work_day", [days]) 

我得到了這個錯誤:

ValueError: Length of values does not match length of index

有什么建議么?

謝謝您的幫助

假設您是輸入工作日的人,我想您可以這樣做:

data = {'year': [2020, 2020, 2021, 2023, 2022], 
        'month': [1, 2, 3, 4, 6]} 
 
df = pd.DataFrame(data)
 
df.insert(2, "work_day", [20,20,23,21,22]) 

其中2是新列的 position,而不僅僅是在末尾, work_day是名稱,並且列表包含每一行的值。

編輯:使用 NumPy

import numpy as np
import pandas as pd

days = np.busday_count( '2021-02', '2021-03' )
data = {'year': [2021], 
        'month': ['february']} 
 
df = pd.DataFrame(data)
 
df.insert(2, "work_day", [days]) 

使用busday_count指定要查看工作日的開始和結束日期。結果:

   year     month  work_day
0  2021  february  20

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM