Конечно, есть более оптимальное решение, но вот мое предложение:
import pandas as pd
dates = ['3-Apr-2018', '4-Apr-2018', '15-Apr-2018', '5-May-2018', '3-Jun-2018']
prices = [300, 200, 100, 900, 200]
list_of_tuples = list(zip(dates, prices))
df = pd.DataFrame(list_of_tuples, columns=['dates', 'prices'])
#solution:
df['dates'] = pd.to_datetime(df['dates'])
for index, r in df.iterrows():
df['c_' + str(index)] = (df['dates'] - r['dates']).apply(lambda x: 1 if pd.Timedelta(0, unit='d')< x <pd.Timedelta(32, unit='d') else 0)
df['m'] = df.groupby(df['dates'].dt.month).ngroup()
d31 = [df.index[df[col] == 1].tolist() for col in df if col.startswith('c_') and df[col].sum() > 1]
months = [*(df.groupby(df['dates'].dt.month).groups.values())]
months = [m.to_list() for m in months]
d31_months = d31 + months
Выход немного отличается от вашего, но я не понимаю, почему не включайте [3], [4]
в течение нескольких месяцев:
[[1, 2], [2, 3], [0, 1, 2], [3], [4]]
Мне удалось его немного реорганизовать:
months = [list(m) for m in df.groupby(df['dates'].dt.month).indices.values()]
diff = lambda r: (df['dates'] - r['dates']).apply(lambda x: 1 if pd.Timedelta(0, unit='d') < x < pd.Timedelta(32, unit='d') else 0)
d31 = [list(np.nonzero(df.index[diff(r)])[0]) for i, r in df.iterrows() if diff(r).sum() > 1]
d31_months = d31 + months