Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Pandas support quarterly dates of the form yyyyQp (e.g. 2013Q2)?

Tags:

python

pandas

I'm importing a CSV of macroeconomic data and haven't been able to figure out how to get Pandas to interpret this type of date. Is there a way to do it automatically or will I need to parse it myself?

When I ask the parser to try, I get:

  File "datetime.pxd", line 133, in datetime._string_to_dts (pandas/tslib.c:31399)ValueError: Unable to parse 2002Q1
like image 487
kdamica Avatar asked May 26 '13 23:05

kdamica


People also ask

Does pandas have a date format?

By default pandas datetime format is YYYY-MM-DD ( %Y-%m-%d ). In this article, I will explain how to convert this datetime to a String format for example to MM/DD/YYYY ( %m/%d/%Y ) and to any other string date pattern.


1 Answers

Since the pd.Period can parse quarterly periods, you could use it as the custom date_parser. Then, to convert the date to the last day of the quarter, you could use map and the end_time attribute:

import pandas as pd

text = '''\
date    val
2013Q2 100
2013Q3 120
'''

filename = '/tmp/data'
with open(filename, 'w') as f:
    f.write(text)
df = pd.read_table(filename, sep='\s+', date_parser=pd.Period, parse_dates=[0])
df['date'] = df['date'].map(lambda x: x.end_time.date())

print(df)
#          date  val
# 0  2013-06-30  100
# 1  2013-09-30  120
like image 99
unutbu Avatar answered Oct 07 '22 00:10

unutbu