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"))
答案 0 :(得分:4)
您可以使用str.replace
,然后按str[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