我正在嘗試轉換具有真正混合日期格式的列。我已經在 SO 上嘗試了一些東西,但仍然沒有得到有效的解決方案。我嘗試將列更改為“字串”,還嘗試將浮點數轉換為 int。
資料
date
1 43076.0
2 43077
3 07 Dec 2017
4 2021-12-22 00:00:00
嘗試修復 Excel 日期和“2017 年 12 月 7 日”樣式的代碼
d = ['43076.0', '43077', '07 Dec 2017', '2021-12-22 00:00:00']
df = pd.DataFrame(d, columns=['date'])
date1 = pd.to_datetime(df['date'], errors='coerce', format='%d %a %Y')
date2 = pd.to_datetime(df['date'], errors='coerce', unit='D', origin='1899-12-30')
frame_clean[col] = date2.fillna(date1)
錯誤
Name: StartDate, Length: 16189, dtype: object' is not compatible with origin='1899-12-30'; it must be numeric with a unit specified
我喜歡這個解決方案,而不是使用 apply 來降低速度。但我正在努力讓它發揮作用。
編輯
分解@FObersteiner 解決方案以便更好地理解。
轉換簡單的日期
df['datetime'] = pd.to_datetime(df['date'], errors='coerce')
0 NaT
1 NaT
2 2018-12-07
3 2021-12-22
隔離數字行
m = pd.to_numeric(df['date'], errors='coerce').notna()
m
0 True
1 True
2 False
3 False
將數字行轉換為浮點數
df['date'][m].astype(float)
0 43080.0
1 43077.0
將數字行轉換為浮點數,然后轉換為 dt 物件
pd.to_datetime(df['date'][m].astype(float), errors='coerce', unit='D', origin='1899-12-30')
0 2017-12-11
1 2017-12-08
將它們拉在一起并帶回簡單的日期行
df.loc[m, 'datetime'] = pd.to_datetime(df['date'][m].astype(float), errors='coerce', unit='D', origin='1899-12-30')
print(df)
uj5u.com熱心網友回復:
對于給定的示例,使用掩碼分別轉換數字和非數字資料:
import pandas as pd
df = pd.DataFrame({'date':['43076.0', '43077', '07 Dec 2017', '2021-12-22 00:00:00']})
df['datetime'] = pd.to_datetime(df['date'], errors='coerce')
m = pd.to_numeric(df['date'], errors='coerce').notna()
df.loc[m, 'datetime'] = pd.to_datetime(df['date'][m].astype(float), errors='coerce', unit='D', origin='1899-12-30')
print(df)
date datetime
0 43076.0 2017-12-07
1 43077 2017-12-08
2 07 Dec 2017 2017-12-07
3 2021-12-22 00:00:00 2021-12-22
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432155.html
下一篇:如何從日期時間索引中獲取浮點值
