简体   繁体   English

按月的工作日对 DataFrame 进行分组

[英]Group DataFrame by Business Day of Month

I am trying to group a Pandas DataFrame that is indexed by date by the business day of month, approx 22/month.我正在尝试对 Pandas DataFrame进行分组,该数据DataFrame的工作日(大约 22/月)按日期编制索引。

I would like to return a result that contains 22 rows with mean of some value in `DataFrame.我想返回一个结果,其中包含 22 行,在`DataFrame 中具有某个值的平均值。

I can by day of month but cant seem to figure out how to by business day.我可以按月的某天,但似乎无法弄清楚如何按工作日。

Is there a function that will return the business day of month of a date?是否有一个函数可以返回某个日期的月份的工作日?

if someone could provide a simple example that would be most appreciated.如果有人能提供一个简单的例子,那将是最感激的。

Assuming your dates are in the index (if not use 'set_index):假设您的日期在索引中(如果不使用“set_index”):

df.groupby(pd.TimeGrouper('B')) 

See time series functionality .请参阅时间序列功能

I think what the question is asking is to groupby business day of month - the other answer just seems to resample the data to the nearest business day (at least for me).我认为问题是按月的工作日分组 - 另一个答案似乎只是将数据重新采样到最近的工作日(至少对我而言)。 This code returns a groupby object with 22 rows此代码返回一个具有 22 行的 groupby 对象

from datetime import date
import pandas as pd
import numpy as np

d = pd.Series(np.random.randn(1000), index=pd.bdate_range(start='01 Jan 2018', periods=1000))
def to_bday_of_month(dt):
    month_start = date(dt.year, dt.month, 1)
    return np.busday_count(month_start, dt)

day_of_month = [to_bday_of_month(dt) for dt in d.index.date]
d.groupby(day_of_month).mean()

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

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