[英]how to create a pandas data frame with the first days and the last days of Months
我想創建這樣一個數據框:
0 2022-01-01
1 2022-01-31
2 2022-02-01
3 2022-02-28
4 2022-03-01
5 2022-03-31
我嘗試使用它,但沒有弄明白。
dfpd.date_range(start = '1/1/2022', end ='6/30/2022', freq='M'),
您可以利用列表理解和.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
您可以使用:
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
可能不是那里最干凈的答案,但它確實有效......
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'])
退貨
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.