简体   繁体   中英

Create date column from quarter and year columns

Let's say I have the following columns in a dataframe.

temp = pd.DataFrame({'quarter': [1, 2, 1, 3, 4],
                   'year': [1994, 1995, 2001, 1997, 2014]})

How can I create a new 'date' column that represents the time with a datetime object? Let quarter 1 be Jan 1, quarter 2 be March 1, quarter 3 be June 1, and quarter 4 be Sept 1. For example, if it were quarter 1 in 1994, the 'date' column should have 1994-01-01.

You can use pd.to_datetime :

pd.to_datetime(temp['year'].astype(str) + 'Q' + temp['quarter'].astype(str))

Output:

0   1994-01-01
1   1995-04-01
2   2001-01-01
3   1997-07-01
4   2014-10-01
dtype: datetime64[ns]

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