Zakk Yang
Zakk Yang

Reputation: 149

how to create a dataframe like this with quick solution?

d = {
'month': [5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5],
'year': [
    2018,
    2018,
    2018,
    2018,
    2018,
    2018,
    2018,
    2018,
    2019,
    2019,
    2019,
    2019,
    2019
]}
df = pd.DataFrame(data=d)
df

Instead of manually input the month and year, is there any good solution to have a loop to identify which year to stop, and the month will be increased accordingly from 1 to 12?

Upvotes: 1

Views: 31

Answers (1)

anky
anky

Reputation: 75100

IIUC, I can think of pd.date_range():

s=pd.date_range('May 2018','June 2019',freq='M')
df=pd.DataFrame({'month':s.month,'year':s.year})
print(df)

    month  year
0       5  2018
1       6  2018
2       7  2018
3       8  2018
4       9  2018
5      10  2018
6      11  2018
7      12  2018
8       1  2019
9       2  2019
10      3  2019
11      4  2019
12      5  2019

Upvotes: 2

Related Questions