简体   繁体   中英

how to create a pandas data frame with the first days and the last days of Months

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'), 

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

You can use:

import pandas as pd
start = '2022-01-01'
end = '2022-06-30'
first_day = pd.date_range(start, end, freq='MS').astype(str) #get first day of month given range
last_day = pd.date_range(start, end, freq='M').astype(str) #get last day of month given range
df=pd.DataFrame({'first_day':first_day,'last_day':last_day})
df = df.stack().reset_index(drop=True)

Output:

    0
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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