Python清理日期仅在Pandas中转换为年份

ccs*_*csv 4 python pandas data-cleaning

我有一个大型数据集,一些用户将数据放在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
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用将日期转换为年份

df['year']=df['datestart'].astype('timedelta64[Y]')
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误:

ValueError: Value cannot be converted into object Numpy Time delta
Run Code Online (Sandbox Code Playgroud)

使用Datetime64

df['year']=pd.to_datetime(df['datestart']).astype('datetime64[Y]')
Run Code Online (Sandbox Code Playgroud)

它给了:

"ValueError: Error parsing datetime string ""03/13/2014"" at position 2"
Run Code Online (Sandbox Code Playgroud)

由于该栏目由用户填写,大部分都采用这种格式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']  
Run Code Online (Sandbox Code Playgroud)

和使用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]]        
Run Code Online (Sandbox Code Playgroud)

jor*_*ris 5

首先必须将具有日期值的列转换为datetime's to_datetime():

df['datestart'] = pd.to_datetime(df['datestart'], coerce=True)
Run Code Online (Sandbox Code Playgroud)

这应该通常灵活地解析不同的格式(coerce=True这里将无效日期转换为非常重要NaT).

如果你想要年份部分的日期,你可以做以下(似乎直接在pandas列上做astype给出一个错误,但values你可以得到底层的numpy数组):

df['datestart'].values.astype('datetime64[Y]')
Run Code Online (Sandbox Code Playgroud)

这样做的问题是,由于该NaT值将此值分配给列时再次出现错误(这似乎是一个错误,您可以通过执行此操作来解决此问题df = df.dropna()).但是,当你将它分配给一个列时,它会被转换回一个,datetime64[ns]因为这是pandas存储日期时间的方式.所以我个人认为如果你想要一个有年份的专栏,你可以更好地做到以下几点:

df['year'] =  pd.DatetimeIndex(df['datestart']).year
Run Code Online (Sandbox Code Playgroud)

最后一个将以整数形式返回年份.

  • 刚试过,也试过`error ='ignore'`.所以我做了这个'.df ['year'] = pd.to_datetime(df ['datestart'],coerce = True,errors ='ignore').astype('datetime64 [Y]')`并得到一个错误`TypeError :不能将[datetime64 [ns]]到[datetime64 [Y]]的日期时间类型化为``我认为充满零(00/00/0000)的点被误解为纳秒并且忽略没有捕获它. (2认同)