Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

python - Pandas: generate timeseries datetime features

I have a DF that has date as Datetime, ranging from Jan 2013 to Dec 2015. I want to create a time series feature, indicating that each month has a date_block_num, increases by one every month.

For example, Jan 2013 is 0, Feb 2013 is 1,..., Dec 2013 is 11, Jan 2014 is 12, Feb 2014 is 13 and so on.

I can use a simple iterrows() to do this, but I wonder if there is a better way?

question from:https://stackoverflow.com/questions/65931398/pandas-generate-timeseries-datetime-features

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your data has all the months, you can use factorize:

DF['date'].dt.to_period('M').sort_values().factorize()

Or, you can try some math:

years = DF['date'].dt.year
months = DF['date'].dt.month

DF['date_block'] = (years*12 + months) - 2013*12

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...