我相信您的数据包含NaNs 或一些非日期时间值:
tyc = pd.DataFrame({'startDate':['2016-05-03','2017-05-03', np.nan],
'col':[1,2,3]})
print (tyc)
col startDate
0 1 2016-05-03
1 2 2017-05-03
2 3 NaN
使用str[0] 首先返回每行的第一个列表值。但是有问题 - 一些NaNs,不能转换为int(设计) - 所以输出是浮点数:
print (tyc.startDate.str.split('-').str[0].astype(float))
0 2016.0
1 2017.0
2 NaN
Name: startDate, dtype: float64
另一种解决方案是通过to_datetime 转换为日期时间并通过year 解析年份:
print (pd.to_datetime(tyc.startDate, errors='coerce'))
0 2016-05-03
1 2017-05-03
2 NaT
Name: startDate, dtype: datetime64[ns]
print (pd.to_datetime(tyc.startDate, errors='coerce').dt.year)
0 2016.0
1 2017.0
2 NaN
Name: startDate, dtype: float64
删除NaNs的解决方案:
tyc['year'] = pd.to_datetime(tyc.startDate, errors='coerce').dt.year
print (tyc)
col startDate year
0 1 2016-05-03 2016.0
1 2 2017-05-03 2017.0
2 3 NaN NaN
1.
通过dropna删除所有带有NaNs的行,然后转换为int:
tyc = tyc.dropna(subset=['year'])
tyc['year'] = tyc['year'].astype(int)
print (tyc)
col startDate year
0 1 2016-05-03 2016
1 2 2017-05-03 2017
2.
将 NaNs 替换为一些 int 值,例如 1 到 fillna,然后转换为 int:
tyc['year'] = tyc['year'].fillna(1).astype(int)
print (tyc)
col startDate year
0 1 2016-05-03 2016
1 2 2017-05-03 2017
2 3 NaN 1