python - How to convert Period string to actual Period type -


i have column of data such '1971q1', '1972q2', etc. (year followed quarter) when do:

print(type(df.quarterly)) 

the answer series

what need "cast"/convert column genuine pd.period type can simple time algebra it. thank you

you can use pd.periodindex() method.

assume have following df:

in [517]: x out[517]:   str_col 0  1971q1 1  1971q2 2  1971q3 3  1971q4 4  1972q1 5  1972q2 6  1972q3 7  1972q4  in [518]: x.dtypes out[518]: str_col    object dtype: object 

let's create new 'period' column:

in [519]: x['period'] = pd.periodindex(x.str_col, freq='q')  in [520]: x out[520]:   str_col period 0  1971q1 1971q1 1  1971q2 1971q2 2  1971q3 1971q3 3  1971q4 1971q4 4  1972q1 1972q1 5  1972q2 1972q2 6  1972q3 1972q3 7  1972q4 1972q4  in [521]: x.dtypes out[521]: str_col    object period     object dtype: object 

now can "time algebra", example let's subtract 1 quarter each period:

in [525]: x.period - 1 out[525]: 0   1970q4 1   1971q1 2   1971q2 3   1971q3 4   1971q4 5   1972q1 6   1972q2 7   1972q3 name: period, dtype: object 

alternatively can cast str_col column regular pandas/numpy datetime:

in [527]: pd.to_datetime(x.str_col, errors='coerce') out[527]: 0   1971-01-01 1   1971-04-01 2   1971-07-01 3   1971-10-01 4   1972-01-01 5   1972-04-01 6   1972-07-01 7   1972-10-01 name: str_col, dtype: datetime64[ns] 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -