DataFrame看起来像:
OPENED
0 2004-07-28
1 2010-03-02
2 2005-10-26
3 2006-06-30
4 2012-09-21
我成功地将它们转换成我想要的格式,但是它似乎非常低效。
OPENED
0 40728
1 100302
2 51026
3 60630
4 120921
我用于日期转换的代码是:
df['OPENED'] = pd.to_datetime(df.OPENED, format='%Y-%m-%d')
df['OPENED'] = df['OPENED'].apply(lambda x: x.strftime('%y%m%d'))
df['OPENED'] = df['OPENED'].apply(lambda i: str(i))
df['OPENED'] = df['OPENED'].apply(lambda s: s.lstrip("0"))
您可以使用str.replace
,然后通过str[2:]
删除前2个字符,最后通过str.lstrip
删除前导0
:
print (type(df.ix[0,'OPENED']))
<class 'str'>
print (df.OPENED.dtype)
object
print (df.OPENED.str.replace('-','').str[2:].str.lstrip('0'))
0 40728
1 100302
2 51026
3 60630
4 120921
Name: OPENED, dtype: object
如果dtype已经是datetime
,请使用strftime
和str.lstrip
:
print (type(df.ix[0,'OPENED']))
<class 'pandas.tslib.Timestamp'>
print (df.OPENED.dtype)
datetime64[ns]
print (df.OPENED.dt.strftime('%y%m%d').str.lstrip('0'))
0 40728
1 100302
2 51026
3 60630
4 120921
Name: OPENED, dtype: object
感谢Jon Clements
的评论:
print (df['OPENED'].apply(lambda L: '{0}{1:%m%d}'.format(L.year % 100, L)))
0 40728
1 100302
2 51026
3 60630
4 120921
Name: OPENED, dtype: object