簡體   English   中英

如何在熊貓 date_range 方法中包含結束日期?

[英]How to include end date in pandas date_range method?

pd.date_range('2016-01', '2016-05', freq='M', ).strftime('%Y-%m') ,上個月是2016-04 ,但我期待它是2016-05 在我看來,這個函數的行為類似於range方法,其中 end 參數不包含在返回數組中。

有沒有辦法在不處理結束月份的字符串的情況下獲取包含在返回數組中的結束月份?

一種不費吹灰之力搞清楚月份結束的方法。

pd.date_range(*(pd.to_datetime(['2016-01', '2016-05']) + pd.offsets.MonthEnd()), freq='M')

DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30',
           '2016-05-31'],
          dtype='datetime64[ns]', freq='M')

您可以在初始化date_range后使用.union添加下一個邏輯值。 它應該在任何頻率下都可以正常工作:

d = pd.date_range('2016-01', '2016-05', freq='M')
d = d.union([d[-1] + 1]).strftime('%Y-%m')

或者,您可以使用period_range而不是date_range 根據您打算做什么,這可能不是正確的使用方法,但它可以滿足您的問題:

pd.period_range('2016-01', '2016-05', freq='M').strftime('%Y-%m')

在任何一種情況下,結果輸出都符合預期:

['2016-01' '2016-02' '2016-03' '2016-04' '2016-05']

對於后來的人群。 您也可以嘗試使用 Month-Start 頻率。

>>> pd.date_range('2016-01', '2016-05', freq='MS', format = "%Y-%m" )
DatetimeIndex(['2016-01-01', '2016-02-01', '2016-03-01', '2016-04-01',
               '2016-05-01'],
              dtype='datetime64[ns]', freq='MS')

date_range調用中指定日期時包括日期

pd.date_range('2016-01-31', '2016-05-31', freq='M', ).strftime('%Y-%m')

array(['2016-01', '2016-02', '2016-03', '2016-04', '2016-05'], 
      dtype='|S7')

在數據框中使用日期時間對象時,我遇到了類似的問題。 我會通過 .min() 和 .max() 函數設置邊界,然后使用 pd.date_range 函數填充缺失的日期。 不幸的是,返回的 list/df 缺少最大值。

我為此找到了兩個解決方法:

1) 在 pd.date_range 函數中添加“closed = None”參數。 這在下面的示例中起作用; 但是,僅在使用數據幀時它對我不起作用(不知道為什么)。

2) 如果選項 #1 不起作用,那么您可以使用 datetime.timedelta() 函數添加一個額外的單位(在這種情況下是一天)。 在下面的情況下,它超過了一天的索引,但如果 date_range 函數沒有給你完整的范圍,它可以為你工作。

import pandas as pd
import datetime as dt 

#List of dates as strings
time_series = ['2020-01-01', '2020-01-03', '2020-01-5', '2020-01-6', '2020-01-7']

#Creates dataframe with time data that is converted to datetime object 
raw_data_df = pd.DataFrame(pd.to_datetime(time_series), columns = ['Raw_Time_Series'])

#Creates an indexed_time list that includes missing dates and the full time range

#Option No. 1 is to use the closed = None parameter choice. 
indexed_time = pd.date_range(start = raw_data_df.Raw_Time_Series.min(),end = raw_data_df.Raw_Time_Series.max(),freq='D',closed= None)
print('indexed_time option #! = ', indexed_time)

#Option No. 2 if the function allows you to extend the time by one unit (in this case day) 
#by using the datetime.timedelta function to get what you need. 
indexed_time = pd.date_range(start = raw_data_df.Raw_Time_Series.min(),end = raw_data_df.Raw_Time_Series.max()+dt.timedelta(days=1),freq='D')
print('indexed_time option #2 = ', indexed_time)

#In this case you over index by an extra day because the date_range function works properly
#However, if the "closed = none" parameters doesn't extend through the full range then this is a good work around 

我不這么認為。 您需要添加 (n+1) 邊界

   pd.date_range('2016-01', '2016-06', freq='M' ).strftime('%Y-%m')

開始和結束日期嚴格包括在內。 因此,如果指定,它不會生成這些日期之外的任何日期。 http://pandas.pydata.org/pandas-docs/stable/timeseries.html

無論哪種方式,您都必須手動添加一些信息。 我相信再增加一個月的工作量並不大。

這個問題的解釋是函數pd.to_datetime()默認將'%Y-%m'日期字符串轉換為月份的第一天日期時間,或'%Y-%m-01'

>>> pd.to_datetime('2016-05')
Timestamp('2016-05-01 00:00:00')
>>> pd.date_range('2016-01', '2016-02')
DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',
               '2016-01-05', '2016-01-06', '2016-01-07', '2016-01-08',
               '2016-01-09', '2016-01-10', '2016-01-11', '2016-01-12',
               '2016-01-13', '2016-01-14', '2016-01-15', '2016-01-16',
               '2016-01-17', '2016-01-18', '2016-01-19', '2016-01-20',
               '2016-01-21', '2016-01-22', '2016-01-23', '2016-01-24',
               '2016-01-25', '2016-01-26', '2016-01-27', '2016-01-28',
               '2016-01-29', '2016-01-30', '2016-01-31', '2016-02-01'],
              dtype='datetime64[ns]', freq='D')

然后一切都由此而來。 指定freq='M'包括 2016-01-01 和 2016-05-01 之間的月末,這是您收到的列表,不包括 2016-05-31。 但是指定月份開始'MS'就像第二個答案提供的那樣,包括 2016-05-01,因為它在范圍內。 pd.date_range()默認行為與range方法不同,因為包括了結束。 文檔

封閉控制是否包括邊界上的開始和結束。 默認包括兩端的邊界點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM