繁体   English   中英

如何使用月份的第一天和最后几天创建 pandas 数据框

[英]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.

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