Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include end date in pandas date_range method?

From pd.date_range('2016-01', '2016-05', freq='M', ).strftime('%Y-%m'), the last month is 2016-04, but I was expecting it to be 2016-05. It seems to me this function is behaving like the range method, where the end parameter is not included in the returning array.

Is there a way to get the end month included in the returning array, without processing the string for the end month?

like image 595
srodriguex Avatar asked Jun 17 '16 21:06

srodriguex


People also ask

How do you create a date range in pandas?

Specifying the valuesSpecify start and end , with the default daily frequency. Specify start and periods , the number of periods (days). Specify end and periods , the number of periods (days). Specify start , end , and periods ; the frequency is generated automatically (linearly spaced).

What does PD Date_range do?

You'll use pd. date_range when you need to have a clean series of dates to reindex your DataFrame. Pseudo Code: Create a range of timestamps at a specified start and end.

How does pandas handle missing date values?

To add missing dates to Python Pandas DataFrame, we can use the DatetimeIndex instance's reindex method. We create a date range index with idx = pd. date_range('09-01-2020', '09-30-2020') .


1 Answers

A way to do it without messing with figuring out month ends yourself.

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')
like image 77
piRSquared Avatar answered Sep 24 '22 08:09

piRSquared