我正在导入CSV的宏观经济数据,并且无法弄清楚如何让Pandas解释这种类型的日期.有没有办法自动完成它或我需要自己解析它?
当我要求解析器尝试时,我得到:
File "datetime.pxd", line 133, in datetime._string_to_dts (pandas/tslib.c:31399)ValueError: Unable to parse 2002Q1
Run Code Online (Sandbox Code Playgroud)
由于pd.Period可以解析季度时段,因此您可以将其用作自定义date_parser.然后,要将日期转换为季度的最后一天,您可以使用map和end_time属性:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1857 次 |
| 最近记录: |