这是一个关于计算两个日期之间的天数范围的类似问题的转折,这两个日期被划分到每月的列Pandas: monthly date range with number of days中。
在我的数据框中,我有两列df ['begin_date']和df ['end_date']。我想计算特定月份中有多少天。
df['PTO_End_Date'] = pd.to_datetime(df.PTO_End_Date)
df['PTO_Start_Date'] = pd.to_datetime(df.PTO_Start_Date)
df['Days'] = (df['PTO_End_Date'] - df['PTO_Start_Date']).dt.days
df['Feb-2023'] =
df['Mar-2023'] =
df['Apr-2023'] =
我可以计算日期之间的天数,但日期跨越多个月,我试图将日期划分到特定的月份。正在寻找一种方法将此系列样式代码转换为Pandas列。
s = pd.Series(index=pd.date_range(df['PTO_Start_Date'], df['PTO_End_Date']), dtype='float64')
2条答案
按热度按时间mznpcxlj1#
@亚瑟假设你有100条记录,那么最好为每条记录创建一个DataFrame。虽然这需要更多的代码。但这是可行的。
你可以利用几个函数,比如df.pipe()来传递函数。
这个例子有20个日期,但它可以缩放到任何数字。
6yt4nkrj2#
有一个完整的代码在这里:
这将保留我所有的原始列,并在它们自己的列中添加每月工作日数。Freq =“B”表示工作日,Freq=“D”表示总天数。