在 Python/pandas 中格式化每月日期

Formatting Monthly dates in Python/pandas

我想修改 Monthly_idxs 以便它输出从月份的开始分钟开始的每月数据范围 -01 00:00:00+00:00 而不是当前输出。我还想包括初始索引的月份是十月,但输出从十一月开始初始 Monthly_idxs。我怎样才能获得下面的预期输出?

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')

输出:

['2015-11-01 13:40:00+00:00', '2015-12-01 13:40:00+00:00',
               '2016-01-01 13:40:00+00:00']

预期输出:

['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']

我们可以使用 round and 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()

输出:

['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']

感谢@MrFuppes 的 DateOffset 想法。

您的列表转换发生得太早了。您可以在数据框上使用 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)

输出:

['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']