我相信您的數據包含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
接受。謝謝 –