繁体   English   中英

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

[英]Formatting Monthly dates in Python/pandas

我想修改Monthly_idxs以便它输出从当月开始分钟-01 00:00:00+00:00开始的每月数据范围,而不是当前的 output。 我还想包括初始索引为 10 月的月份,但 output 从 11 月开始初始Monthly_idxs 我怎样才能得到下面的预期 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:

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

预期 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']

我们可以使用roundDateOffset编写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:

['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想法。

您的列表转换发生得太快了。 您可以在 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:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM