我有一個包含十多列的 Pandas 資料框,其中大多數列是 Pandas 的“物件”型別。
我需要將其中三個列從“物件”型別轉換為“日期時間”型別并寫回現有的資料框列(以執行“就地更新”)。
我只使用以下代碼作為一列的起點,并計劃對其他兩列進行擴展,但它不起作用。
' bigframe ' 資料框有許多重復的行。我正在洗掉基于“ incidentId ”的重復行并將唯一行分配給下面的“ alerts ”。
alerts = bigframe.drop_duplicates(subset=['incidentId'])
alerts['firstEventTime'] = pd.to_datetime(alerts['firstEventTime'])
alerts['firstEventTime']的內容類似于' 2021-01-27 22:34:05.991031 00:00 '
我收到以下警告,但代碼執行完成且沒有錯誤。
“試圖在資料幀的切片副本上設定一個值。嘗試使用 .loc[row_indexer,col_indexer] = value 代替”
當我輸入“ a lerts.dtypes ”時,我仍然看到該列被列為“ object ”型別。所以,我假設由于某種原因操作沒有寫回原始資料幀。
我搜索了互聯網,上面列出的代碼應該可以作業,但它沒有。所以我一定做錯了什么,但我找不到。你能告訴我我做錯了什么嗎?
謝謝!
uj5u.com熱心網友回復:
這里有兩個不相關的問題;
#1DataFrame.drop_duplicates回傳現有 df 的切片,而不是新的 df。您可以通過將結果明確地復制到新的 df 來避免警告。
#2 pandas datetime dtype 無法處理一個系列中的混合 UTC 偏移量。在這種情況下,它回退到使用 Python 的日期時間,即元素的型別為 datetime.datetime,顯示為“物件”。您可以通過使用關鍵字轉換為 UTC 來處理此問題utc=True。
前任:
bigframe = pd.DataFrame({'incidentId': [1,1,2],
'firstEventTime': ['2021-01-27 22:34:05.991031 00:00',
'2021-01-27 22:34:05.991031 00:00',
'2022-01-18 20:34:52']})
# avoid the warning by explicitly calling .copy():
alerts = bigframe.drop_duplicates(subset=['incidentId']).copy()
# now convert to datetime in UTC, to get a datetime64[ns] dtyped Series:
alerts['firstEventTime'] = pd.to_datetime(alerts['firstEventTime'], utc=True)
alerts['firstEventTime']
# 0 2021-01-27 22:34:05.991031 00:00
# 2 2022-01-18 20:34:52 00:00
# Name: firstEventTime, dtype: datetime64[ns, UTC]
請注意,如果未指定 UTC 偏移量,pandas 將假定輸入為 UTC。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421491.html
標籤:
上一篇:每月隨機抽樣一次pandas
