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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With