[英]convert to datetime and format date in pandas in a single oneliner
我有一個 dataframe 有兩列包含未格式化的日期。
這些列中的數據如下:2011-06-10T00:00:00.000+02:00
我想只獲取日期並對其進行格式化。
在 Jupyter 筆記本中,我執行以下操作:
sections['produced'] = pd.to_datetime(sections['produced'])
sections['produced'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in sections['produced']]
sections['updated'] = pd.to_datetime(sections['updated'])
sections['updated'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in sections['updated']]
sections.info()
然后我打印出 dataframe 部分,確實日期打印正確。
但:
sections.info()
仍然告訴我這些列是非空對象而不是日期時間。 為什么?
其次,我的方法似乎在幕后不起作用,即日期類型實際上不是日期。 我應該怎么辦? 最后,代碼對於應該是一個襯里的東西來說是超級冗長的,或者不是? (即 pandas 功能強大但有其局限性)
編輯1:回答一些貢獻者。 我期待日期時間。 只是 2008-02-02 只是這一天。 所以在做的時候:
sections['updated'] = pd.to_datetime(sections['updated'])
日期類型被轉換。 但是在下一步做的時候:
sections['produced'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in sections['produced']]
所以這里的目的是a)轉換為日期時間格式b)獲取日期格式2008-01-02,我不關心秒c)它必須在jupyter筆記本中打印出來,即日期
只需在to_datetime()
方法中傳遞errors
參數並將其設置為“強制” :-
sections['produced'] = pd.to_datetime(sections['produced'],errors='coerce')
sections['updated'] = pd.to_datetime(sections['updated'],errors='coerce')
這應該作為一個班輪工作:
df[['produced','updated']] = df[['produced','updated']].apply(lambda x: pd.to_datetime(x,errors='coerce'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.