簡體   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