我有一个大型数据集,一些用户将数据放在 csv 中。我将 CSV 转换为带有panda
. 该列有超过 1000 个条目,这里是一个示例
datestart
5/5/2013
6/12/2013
11/9/2011
4/11/2013
10/16/2011
6/15/2013
6/19/2013
6/16/2013
10/1/2011
1/8/2013
7/15/2013
7/22/2013
7/22/2013
5/5/2013
7/12/2013
7/29/2013
8/1/2013
7/22/2013
3/15/2013
6/17/2013
7/9/2013
3/5/2013
5/10/2013
5/15/2013
6/30/2013
6/30/2013
1/1/2006
00/00/0000
7/1/2013
12/21/2009
8/14/2013
Feb 1 2013
然后我尝试使用将日期转换为年份
df['year']=df['datestart'].astype('timedelta64[Y]')
但它给了我一个错误:
ValueError: Value cannot be converted into object Numpy Time delta
使用日期时间64
df['year']=pd.to_datetime(df['datestart']).astype('datetime64[Y]')
它给了:
"ValueError: Error parsing datetime string ""03/13/2014"" at position 2"
由于该列是用户填写的,因此大多数格式为 MM/DD/YYYY,但有些数据是这样输入的:2013 年 2 月 10 日,有一个像 00/00/0000 这样的条目。我猜不同的格式搞砸了处理。
有没有try loop
, if statement
, 或者我可以跳过这些问题的东西?
如果日期时间失败,我将被迫使用str.extract
同样有效的脚本:
year=df['datestart'].str.extract("(?P<month>[0-9]+)(-|\/)(?P<day>[0-9]+)(-|\/)(?P<year>[0-9]+)")
del df['month'], df['day']
并concat
用来取出一年。
错误df['year']=pd.to_datetime(df['datestart'],coerce=True, errors ='ignore').astype('datetime64[Y]')
消息是:
Message File Name Line Position
Traceback
<module> C:\Users\0\Desktop\python\Example.py 23
astype C:\Python33\lib\site-packages\pandas\core\generic.py 2062
astype C:\Python33\lib\site-packages\pandas\core\internals.py 2491
apply C:\Python33\lib\site-packages\pandas\core\internals.py 3728
astype C:\Python33\lib\site-packages\pandas\core\internals.py 1746
_astype C:\Python33\lib\site-packages\pandas\core\internals.py 470
_astype_nansafe C:\Python33\lib\site-packages\pandas\core\common.py 2222
TypeError: cannot astype a datetimelike from [datetime64[ns]] to [datetime64[Y]]