Home > Back-end >  how to create a pandas data frame with the first days and the last days of Months
how to create a pandas data frame with the first days and the last days of Months

Time:12-13

I would like to create such a data frame:

0 2022-01-01
1 2022-01-31
2 2022-02-01
3 2022-02-28
4 2022-03-01
5 2022-03-31

I tried to use this, however did not figure it out.

dfpd.date_range(start = '1/1/2022', end ='6/30/2022', freq='M'), 

CodePudding user response:

Might not be the cleanest answer out there, but it does work...

import calendar
import pandas as pd

Year2022=[]
for i in list(range(1,13,1 )):
    weekday, numdays = calendar.monthrange(2022, i)
    Year2022.append(str(i) "/1/2022")
    Year2022.append(str(i) "/" str(numdays) "/2022")

df = pd.DataFrame({'DateTime':Year2022})
df['DateTime'] = pd.to_datetime(df['DateTime'])

Returns

df
    DateTime
0   2022-01-01
1   2022-01-31
2   2022-02-01
3   2022-02-28
4   2022-03-01
5   2022-03-31
6   2022-04-01
7   2022-04-30
8   2022-05-01
9   2022-05-31
10  2022-06-01
11  2022-06-30
12  2022-07-01
13  2022-07-31
14  2022-08-01
15  2022-08-31
16  2022-09-01
17  2022-09-30
18  2022-10-01
19  2022-10-31
20  2022-11-01
21  2022-11-30
22  2022-12-01
23  2022-12-31

CodePudding user response:

You can utilize list comprehensions and .offsets:

date_range = pd.date_range(start="1/1/2022", end="6/30/2022", freq="M")
month_spans = [[x   pd.offsets.MonthBegin(-1), x   pd.offsets.MonthEnd(0)] for x in date_range]
dates = [x for sublist in month_spans for x in sublist]
df = pd.Series(dates).to_frame("date")

print(df)

Output:

         date
0  2022-01-01
1  2022-01-31
2  2022-02-01
3  2022-02-28
4  2022-03-01
5  2022-03-31
6  2022-04-01
7  2022-04-30
8  2022-05-01
9  2022-05-31
10 2022-06-01
11 2022-06-30
  • Related