Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 确定给定时间范围的月份并扩展到多行_Python_Pandas_Time_Period - Fatal编程技术网

Python 确定给定时间范围的月份并扩展到多行

Python 确定给定时间范围的月份并扩展到多行,python,pandas,time,period,Python,Pandas,Time,Period,有没有办法从给定的时间范围中提取月份,并将其应用于基于该范围的价格? 也许最好用例子来说明。我有一系列带有报价开始和结束日期的价格: 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

有没有办法从给定的时间范围中提取月份,并将其应用于基于该范围的价格? 也许最好用例子来说明。我有一系列带有报价开始和结束日期的价格:

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
我想要的是一个类似于下面的表,其中月份名称是从时间范围中提取的:

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\u From
Offer\u To
都是日期时间列,您可以使用+然后手动提取月份:

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

@MartijnPieters这是一个合适的副本吗?这个答案的解决方案涉及到其他步骤…@MartijnPieters我重新打开这个问题,因为副本不被批准。这可能是一个更接近的副本:谢谢@Daniel Mesejo,它工作得很好,但有一个警告,即同一个月的范围(即2019/12/01至2019/12/15)将导致nan,我可能会通过过滤和应用dt.month()来纠正这些错误