Reputation: 337
There's a data frame on which I want to perform time series analysis. The data frame contains distinct columns of year and week:
Year Week stateID values
2018 2 231 55
2010 3 231 92
2000 5 231 56
2018 2 321 55
2010 3 321 45
For performing analysis, I want to concatenate year week column to datetime object having the format Year-Week. i.e:
Year-Week stateID values
2018-2 231 55
2010-3 231 92
2000-5 231 56
2018-2 321 55
2010-3 321 45
How can I achieve it in pandas?
Upvotes: 1
Views: 615
Reputation: 153460
IIUC,
df['Year-Week'] = df['Year'].astype(str) + '-' + df['Week'].astype(str)
df['Period'] = pd.to_datetime(df['Year'].astype(str) + '-' + df['Week'].astype(str) + '-' +'0', format='%Y-%W-%w').dt.to_period('W')
Output:
Year Week stateID values Year-Week Period
0 2018 2 231 55 2018-2 2018-01-08/2018-01-14
1 2010 3 231 92 2010-3 2010-01-18/2010-01-24
2 2000 5 231 56 2000-5 2000-01-31/2000-02-06
3 2018 2 321 55 2018-2 2018-01-08/2018-01-14
4 2010 3 321 45 2010-3 2010-01-18/2010-01-24
Upvotes: 1
Reputation: 672
Something like this should work:
df["Year-Week"] = df.Year.astype(str).str.cat(df.Week.astype(str), sep="-")
Upvotes: 0