我相信您的数据包含NaN
S或一些不datetime值:
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]
退货第一李首先每行的st值。但随后有问题 - 一些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
转换为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
对于删除
NaN
小号
解决方案:
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
与NaN
动手清除所有的行,然后浇铸到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。
通过fillna
通过像1
一些int值替换NaN
秒,然后转换为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
非常感谢你的工作得很好! –
嗯,你写评论与另一个解决方案的一些问题,所以另一个解决方案工作很好,所以是否接受? – jezrael
接受。谢谢 –