在python中选择每月的第一天/第十五天加上前后一天

在python中选择每月的第一天/第十五天加上前后一天,python,time-series,Python,Time Series,我想在表格中选择特定的天数来计算每个特定组的平均数。我的桌子大约有9000行,如下所示: 我只想为每个值选择一个值 -一个月的第一个值, -最后一个月的值, -一个月的第二个值, -每15日, -十五号的前一天,, -15日后一天 目的是计算每个特定组的平均值 结果应该如下所示: 我正在绞尽脑汁计算第15次/之前/之后以及“第一次之后” 到目前为止,我尝试的是: import pandas as pd df = pd.read_csv df['Date'] = pd.to_datetime(

我想在表格中选择特定的天数来计算每个特定组的平均数。我的桌子大约有9000行,如下所示:

我只想为每个值选择一个值 -一个月的第一个值, -最后一个月的值, -一个月的第二个值, -每15日, -十五号的前一天,, -15日后一天

目的是计算每个特定组的平均值

结果应该如下所示:

我正在绞尽脑汁计算第15次/之前/之后以及“第一次之后”

到目前为止,我尝试的是:

import pandas as pd
df = pd.read_csv
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

"Average first of month"
dffirst = df[~df.index.to_period('m').duplicated()]
monthly_first = dffirst['Value'].mean()

"Average last of month"
dflast = df.resample("M").max()
monthly_last = dflast['Value'].mean()

谢谢

据我所知,有些日期可能不见了,这让事情变得有点复杂

我要做的是跟踪一个月内第一个/最后一个可用日期的索引,并从那里开始。即,第一个指数+1表示第二个指数,第一个指数+14表示第15个可用日期。然后,平均值的计算非常简单

但是,您必须确保移位索引存在(例如,没有负索引,没有超过数据帧长度的索引)

对于下面的代码,我假设日期在索引列中

# get indices of first dates available
# get indices of beginning of month as list: df.resample("MS").mean().index.tolist()
# list comprehension to get the index of the next value available (method="bfill") in the dataframe
indices_first = np.asarray([df.index.get_loc(d, method="bfill") for d in df.resample("MS").mean().index.tolist()])

# get indices of last dates available
# method is here "ffill" and resample("M")
indices_last = np.asarray([df.index.get_loc(d, method="ffill") for d in df.resample("M").mean().index.tolist()])

# to get indices of 15th dates available
indices_15 = indices_first + 14
indices_15 = indices_15[indices_15 < len(df)]

# to get indices before last
indices_before_last = indices_last - 1
indices_before_last = indices_before_last[indices_15 >= 0]
avg_first = df.iloc[indices_first]['Value'].mean()
avg_15th = df.iloc[indices_15]['Value'].mean()
avg_before_last = df.iloc[indices_before_last]['Value'].mean()
avg_last = df.iloc[indices_last]['Value'].mean()