Pandas日期解析器在缺失时将日期设置为当前

时间:2015-01-05 19:12:29

标签: python pandas

我正在解析提供一个月和一年的固定宽度文件,我想创建一个月份和年份的熊猫日期,使用1作为日期(而不是当月的当天,因为Pandas默认为做)。

df = pd.read_fwf("/file", colspecs=colspecs,header=None,names=names, 
parse_dates= =  {'calendar':['eligYear',"eligMonth"]},keep_date_col=True)

数据示例:

eligyear eligmonth
2012     02
2012     01

理想的结果,天数= 1而不是当月的某天,例如

calendar
2012-02-01
2012-01-01

1 个答案:

答案 0 :(得分:1)

我认为你可以在阅读csv后更好地解析数字到日期时间,这样会更灵活。
例如,你可以这样做:

In [43]: df = pd.read_csv(StringIO(s), sep='\s+')

In [47]: df['calendar'] = pd.to_datetime(df['eligyear']*10000 + df['eligmonth']*100 + 1, format='%Y%m%d')


In [48]: df
Out[48]: 
   eligyear  eligmonth   calendar
0      2012          2 2012-02-01
1      2012          1 2012-01-01