我在 DataFrame 中有主要由日期組成的列。但也可能有字串或空值。我想從列中提取年份,但由于字串值而出錯。有沒有辦法對此應用通用解決方案?不僅要獲得一年或一個月,還要應用可能以此錯誤結束的其他功能。我的意思是,我想了解這個問題的性質以及如何處理它。
代碼就像
dates={'date':['11/03/2019','12/05/2021','','11/03/2021','x'],
'date2':['11/04/2019','12/03/2021','11/06/2021',np.nan,'ab'],
}
df2=pd.DataFrame(dates)
df2['year'] =pd.DatetimeIndex(df2['date']).year
the error messages
未知字串格式:x
先感謝您!
uj5u.com熱心網友回復:
你可以試試這個
dates={'date':['11/03/2019','12/05/2021','','11/03/2021','x'],
'date2':['11/04/2019','12/03/2021','11/06/2021',np.nan,'ab'],
}
df =pd.DataFrame(dates)
df["date"] = pd.to_datetime(df['date'], errors = "coerce")
df["date2"] = pd.to_datetime(df['date2'], errors = "coerce")
df["year1"] = df["date"].dt.year
df["year2"] = df["date2"].dt.year
輸出 -
日期 | 日期2 | 第一年 | 第 2 年 | |
---|---|---|---|---|
0 | 2019-11-03 00:00:00 | 2019-11-04 00:00:00 | 2019.0 | 2019.0 |
1 | 2021-12-05 00:00:00 | 2021-12-03 00:00:00 | 2021.0 | 2021.0 |
2 | 鈉鹽 | 2021-11-06 00:00:00 | 楠 | 2021.0 |
3 | 2021-11-03 00:00:00 | 鈉鹽 | 2021.0 | 楠 |
4 | 鈉鹽 | 鈉鹽 | 楠 | 楠 |
如果您不希望資料框中有任何空值,請df.dropna(inplace = True)
在添加year1
和year2
列之前執行此操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470825.html