确定给定时间范围的月份并扩展到多行
Determine month given time range and expand to multiple rows
有没有办法从给定的时间范围中提取月份,并将其应用于基于该范围的价格?
也许最好通过示例来说明。我有一系列价格以及报价开始和结束日期:
d = {'Price': [12, 11, 14], 'Offer_From': ['2019-10-12', '2019-10-13', '2020-02-01'],'Offer_To': ['2019-12-31', '2019-10-31', '2020-05-31'], }
df = pd.DataFrame(data=d)
df
Price Offer_From Offer_To
0 12 2019-10-12 2019-12-31
1 11 2019-10-13 2019-10-31
2 14 2020-02-01 2020-05-31
我想要的是一个类似于下面的table,其中从时间范围中提取月份名称:
d2 = {'Price': [12,12,12,11,14,14,14,14], 'Month': ['2019-10', '2019-11', '2019-12', '2019-10', '2020-02', '2020-03', '2020-04', '2020-05']}
df2 = pd.DataFrame(data=d2)
df2
Price Month
0 12 2019-10
1 12 2019-11
2 12 2019-12
3 11 2019-10
4 14 2020-02
5 14 2020-03
6 14 2020-04
7 14 2020-05
假设 Offer_From
和 Offer_To
都是 DateTime 列,您可以使用 date_range + explode 然后手动提取月份:
df['Month'] = df[['Offer_From', 'Offer_To']].apply(lambda x: pd.date_range(x[0], x[1], freq='M'), axis=1)
result = df.explode('Month').drop(['Offer_From', 'Offer_To'], axis=1)
result['Month'] = [f'{date.year}-{date.month:02d}' for date in result['Month']]
print(result)
输出
Price Month
0 12 2019-10
0 12 2019-11
0 12 2019-12
1 11 2019-10
2 14 2020-02
2 14 2020-03
2 14 2020-04
2 14 2020-05
有没有办法从给定的时间范围中提取月份,并将其应用于基于该范围的价格? 也许最好通过示例来说明。我有一系列价格以及报价开始和结束日期:
d = {'Price': [12, 11, 14], 'Offer_From': ['2019-10-12', '2019-10-13', '2020-02-01'],'Offer_To': ['2019-12-31', '2019-10-31', '2020-05-31'], }
df = pd.DataFrame(data=d)
df
Price Offer_From Offer_To
0 12 2019-10-12 2019-12-31
1 11 2019-10-13 2019-10-31
2 14 2020-02-01 2020-05-31
我想要的是一个类似于下面的table,其中从时间范围中提取月份名称:
d2 = {'Price': [12,12,12,11,14,14,14,14], 'Month': ['2019-10', '2019-11', '2019-12', '2019-10', '2020-02', '2020-03', '2020-04', '2020-05']}
df2 = pd.DataFrame(data=d2)
df2
Price Month
0 12 2019-10
1 12 2019-11
2 12 2019-12
3 11 2019-10
4 14 2020-02
5 14 2020-03
6 14 2020-04
7 14 2020-05
假设 Offer_From
和 Offer_To
都是 DateTime 列,您可以使用 date_range + explode 然后手动提取月份:
df['Month'] = df[['Offer_From', 'Offer_To']].apply(lambda x: pd.date_range(x[0], x[1], freq='M'), axis=1)
result = df.explode('Month').drop(['Offer_From', 'Offer_To'], axis=1)
result['Month'] = [f'{date.year}-{date.month:02d}' for date in result['Month']]
print(result)
输出
Price Month
0 12 2019-10
0 12 2019-11
0 12 2019-12
1 11 2019-10
2 14 2020-02
2 14 2020-03
2 14 2020-04
2 14 2020-05