[英]Formatting Monthly dates in Python/pandas
I want to modify the Monthly_idxs
so that it outputs the monthly data ranges starting from the beginning minute of the month -01 00:00:00+00:00
instead of the current output.我想修改
Monthly_idxs
以便它输出从当月开始分钟-01 00:00:00+00:00
开始的每月数据范围,而不是当前的 output。 I want to also include the month of the initial index of which is October but the output starts the initial Monthly_idxs
from November.我还想包括初始索引为 10 月的月份,但 output 从 11 月开始初始
Monthly_idxs
。 How would I be able to get the Expected Output below?我怎样才能得到下面的预期 Output?
import pandas as pd
# Creates 1 minute data range between date_range(a, b)
l = (pd.DataFrame(columns=['NULL'],
index=pd.date_range('2015-10-08T13:40:00Z', '2016-01-04T21:00:00Z',
freq='1T'))
.index.strftime('%Y-%m-%dT%H:%M:%SZ')
.tolist()
)
#Month Indexes
Monthly_idxs = pd.date_range(l[0], l[-1], freq='MS')
Output: Output:
['2015-11-01 13:40:00+00:00', '2015-12-01 13:40:00+00:00',
'2016-01-01 13:40:00+00:00']
Expected Output:预期 Output:
['2015-10-01 00:00:00+00:00', '2015-11-01 00:00:00+00:00','2015-12-01 00:00:00+00:00'
'2016-01-01 00:00:00+00:00']
We can write Monthly_idxs
using round
and DateOffset
to get the expected result:我们可以使用
round
和DateOffset
编写Monthly_idxs
以获得预期的结果:
from pandas.tseries.offsets import DateOffset
Monthly_idxs = pd.date_range(pd.Timestamp(min(l)).round('1d') - DateOffset(months=1), pd.Timestamp(max(l)).round('1d'), freq='MS').strftime("%Y-%m-%d %H:%M:%S%z").tolist()
Output: Output:
['2015-10-01 00:00:00+0000',
'2015-11-01 00:00:00+0000',
'2015-12-01 00:00:00+0000',
'2016-01-01 00:00:00+0000']
Thanks to @MrFuppes for the DateOffset
idea.感谢 @MrFuppes 提出的
DateOffset
想法。
Your list conversion occurs too soon.您的列表转换发生得太快了。 You can use
resample
on your dataframe and then use format
to get the string list of your resampled index:您可以在 dataframe 上使用
resample
,然后使用format
获取重采样索引的字符串列表:
df = pd.DataFrame(columns=['NULL'],
index=pd.date_range('2015-10-08T13:40:00Z', '2016-01-04T21:00:00Z',
freq='1T'))
Month_begin = df.resample('MS').asfreq()
Monthly_idxs = Month_begin.index.format()
print(Monthly_idxs)
Output: Output:
['2015-10-01 00:00:00+00:00', '2015-11-01 00:00:00+00:00', '2015-12-01 00:00:00+00:00', '2016-01-01 00:00:00+00:00']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.